【问题标题】:Post an array into MySQL Workbench with Express.js api and mysql package使用 Express.js api 和 mysql 包将数组发布到 MySQL Workbench
【发布时间】:2020-01-12 04:00:07
【问题描述】:

我正在使用 Express.js 和 mysql 包来创建我的 api,但我无法发帖。

这是我目前的代码:

const express = require('express');
const mysql = require('mysql');

const config = mysql.createConnection({
    host: theHost,
    port: thePort,
    user: theUser,
    password: thePass,        
    database: theDB,
});

const app = express();

config.connect(function(err){
    if(!err) {
        console.log("Success");

    } else {
        console.log("Error trying to connect");    
    }
});

app.get("/api/InternalAccess", function(req, res){
    config.query('SELECT * from InternalAccess', (error, result) => {
        if (error) throw error;

        res.send(result);
      });
});

app.post("/api/internalAccess", function(req, res){

    var info = { User: req.body.User, Password: req.body.Password, CreationDate: req.body.CreationDate };

    config.query('INSERT INTO InternalAccess SET ?', info, (error, result) => {
        if (error) throw error;

        res.send(result);
      });
});

app.listen(3000);

我对 get 没有任何问题,它工作正常,但要从邮递员发帖,我收到错误:“无法读取未定义的属性“用户””。我在逃避什么吗?我真的是使用 mysql 包的新手。

我的数据库是 MySQL Workbench,正如我所说,我正在使用 Node.js、Express.js 和 mysql 包。

希望你能帮助我。提前致谢

【问题讨论】:

    标签: mysql node.js express mysql-workbench


    【解决方案1】:

    为了自动填充req.body,您必须use some body-parser middlewares,例如:

    app.use(express.json()) // for parsing application/json
    app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
    

    当然,可能还有多种其他原因(例如,您没有在 postman 中正确构造请求),但缺少设置中间件是我首先要解决的问题。

    【讨论】:

    • 是的!那是……非常感谢。我欠你一杯啤酒
    【解决方案2】:

    似乎req.body 为空。我认为您可能只是缺少 app.js 中的正文解析器。

    var bodyParser = require('body-parser');
    
    var app = express();
    
    // parse application/json
    app.use(bodyParser.json())
    

    在此处查看其他示例:https://expressjs.com/en/resources/middleware/body-parser.html

    【讨论】:

    • 好吧,Tudor 比我快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2019-05-11
    • 2018-03-29
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多