试图在节点js中发出发布请求,但我不断返回一个空的正文

问题描述 投票:0回答:1

This is my project structureAnd this is the Error I receive when I run my program with the command npm run dev

我正在尝试创建一个简单的网页,以允许用户输入其姓名,电子邮件和工作,然后从html表单中获取该信息,然后尝试将其插入到我的mysql数据库中。我的问题是在people.js中,当我尝试打印req.body时,返回的是空的,我不知道为什么。感谢您的帮助,我在下面提供了我的代码。

这是我的app.js

const express = require('express');
const exphbs = require('express-handlebars');
const db = require('./connection');
const people = require('./routes/api/people');

const PORT = process.env.PORT || 3000;
// ---------------------------------------

// starts express application
const app = express();

// Handlebars middleware
// this sets the view engine to handlebars
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Body Parser middleware
// handles raw json posts
// app.use(bodyParser.json());
// this handles for url encoded posts 
// app.use(bodyParser.urlencoded({ extended: true }));

app.listen(PORT, () => console.log("Server listening on port 3000"));
// ---------------------------------------


// create db 
app.get('/createdb', (req, res) => {
    console.log('in create db');
    let sql = 'CREATE DATABASE peopledb';
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
            res.send('DB created... ');
        }
    });
});


// create table
app.get('/createpeopletable', (req, res) => {
    let sql = `CREATE TABLE people (id int AUTO_INCREMENT, name VARCHAR(255), job VARCHAR(255), email VARCHAR(255), PRIMARY KEY (id))`;;
    db.query(sql, (err, result) => {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
            res.send('People table created');
        }
    })
});


// people api route
app.use("/api/people", people);


// route for home page
app.get('/', (req, res) => {
    console.log('reached home page');
    res.render('home');
})

module.exports = app;   

这是connection.js

const mysql = require('mysql');
// This file holds the connection to the server

// Create connection
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'peopledb'
})

// Connect
db.connect((err) => {
    if (err) {
        console.log(err);
    } else {
        console.log('mysql connected');
    }
});

module.exports = db;

这是我的people.js

const express = require('express');
const mysql = require('mysql');
const db = require('../../connection');
const bodyParser = require('body-parser');


// used to route calls specific to people
const router = express.Router();
// router.use(bodyParser.json());
// this handles for submissions 
router.use(bodyParser.urlencoded({ extended: true }));

router.post('/addPerson', (req, res) => {
    console.log(req.headers);
    let person = {
        name: req.body.name,
        email: req.body.email,
        job: req.body.job
    };
    console.log('----------------');
    console.log(req.body);
    console.log('----------------');
    console.log(person);
    let sql = 'INSERT INTO people SET ?';
    console.log("THE query is: " + sql);
    // the question mark is a place holder for the second args in db.query
    let query = db.query(sql, person, (err, result) => {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
            res.send('Person added');
        }
    });
})


module.exports = router; 

这是我的家。把手

<h1>Welcome to my db</h1>
<form action="/api/people/addPerson" enctype="application/x-www-form-urlencoded" method="POST" class="mb-4">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name">
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" id="email">
    </div>
    <div class="form-group">
        <label for="job">Occupation</label>
        <input type="text" class="form-control" id="job">
    </div>
    <div class="form-group">
        <input type="submit" value="Submit" class="btn btn-primary">
    </div>
</form>
<a href="/api/people/addPerson" class="btn btn-light mt-4">Visit API</a>

这是main.handlebars

<!DOCTYPE html>
<html lang="en">
{{!-- This file acts as a wrapper around the other files --}}

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <title>Student app</title>
</head>

<body>
    <div class="container mt-4">
        {{{body}}}
    </div>
</body>

</html>
javascript mysql node.js express handlebars.js
1个回答
0
投票

您需要表单控件上的name,以便浏览器使用默认的表单提交过程来提交该字段

热门问题
推荐问题
最新问题