无法使用Express将数据从邮递员发布到数据库

时间:2019-06-07 14:42:31

标签: express postman

我无法将数据从邮递员发布到mysql数据库 我正在使用快递

我尝试使用Body和Raw x-wwww-form-urlencoded

这是我的代码(是的,所有内容都在同一个文件中,我很抱歉对不起)

var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// default route
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});
// connection configurations
var dbConn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'testexpress'
});

// connect to database
dbConn.connect(); 



// Add a new user  
app.post('/user', function (req, res) {

    let user = req.body.user;

    if (!user) {
        return res.status(400).send({ error:true, message: 'Please provide user' });
    }

    dbConn.query("INSERT INTO users SET ? ", { user: user }, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
    });
});

// set port
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});

module.exports = app;

这是我来自Postman和数据库的屏幕截图错误

Postman error

Database

1 个答案:

答案 0 :(得分:1)

像这样修改您的代码。它应该可以工作

// Add a new user  
app.post('/user', function (req, res) {

    let user = [req.body]
    console.log(user);

    if (!user) {
        return res.status(400).send({ error:true, message: 'Please provide user' });
    }

    dbConn.query("INSERT INTO users SET ? ", user, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
    });
});

您的代码显示此错误消息error:true, message: 'Please provide user,因为每次在您的代码中都会执行条件if (!user),因为 let user = req.body.user 会给出未定义值,因此您将收到该错误,然后其余代码将永远不会执行