我的Node.js服务器出现错误500内部服务器错误

时间:2019-04-02 06:41:05

标签: javascript jquery node.js

我正在将jquery和Node.js用作服务器,并且出现此错误500 Internal Server Error。我希望该按钮将此表单信息插入到我的数据库中。为什么这不起作用?

Controller.js:

'use strict'
var mysql = require('mysql')

const CONN = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'db'
})

module.exports = 
{
    // Adds teacher to table
    addTeacher: (req, res) => {
        let v = req.body;
        console.log(req.body)
        CONN.query('INSERT INTO teacher (name, email) VALUES (?, ?)', 
[v.name, 
        v.email], 
            (error, results, fields) => {
                if(error) {
                    console.log("Error, reaspn: "+error.mysql)
                    res.json(error)
                } else {
                    console.log("Data added succesfully")
                    res.statusCode = 201;
                }
            }) 
    }
}

Server.js:

express = require('express')
var controller = require('./controller')
var app = express();
var port = 3001;

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
} 

app.use(allowCrossDomain)

// REST API

app.route("/Teachers")
    .post(controller.addTeacher)

app.listen(port, () => {
    console.log("Server is listening port "+port)
})

JQuery和HTML:

<form id="form1">
    <input type="text" placeholder="Name" name="name"/>
    <input type="text" placeholder="Email" name="email"/>
</form>
<button id="addTeacher1">Test</button>
    <script>
        $(function() {
            $("#addTeacher1").click(function() {
                var addons = $("#form1").serialize();
                $.post("http://localhost:3001/teachers",
                    addons
                ).done ( (data, status, jqxhr) => {
                    console.log("Done")
                }).fail( (jqxhr, status, error) => {
                    console.log("status= "+status+", error: "+error);
                });
        })
    })
</script>

req.body在console.log中未定义,因此该服务器似乎无法以某种方式从HTML获取数据。有什么想法吗?

edit:这是我在浏览器控制台上遇到的错误:

jquery-3.3.1.min.js:2 POST http://localhost:3001/teachers 500 (Internal Server Error)

这就是我在CMD中得到的内容:

undefined
TypeError: Cannot read property 'name' of undefined
    at addTeacher (C:\Something\SERVER\controller.js:69:74)

这指向controller.js中的CONN.query行

0 个答案:

没有答案