gpt4 book ai didi

mysql - Nodejs : Post method url body parser shows undefined

转载 作者:行者123 更新时间:2023-11-29 18:08:35 26 4
gpt4 key购买 nike

我想使用 url post params 来执行 mysql 查询。当我通过 postman 发帖时,我在 mysql 命令期间收到错误。我不知道这段代码有什么问题。这是我的代码

var express    = require('express');   
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('MD5');
var con = mysql.createConnection({
host: "localhost",
user: "shoaib",
password: "",
database: "watch"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

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

var port = process.env.PORT || 8080;
var router = express.Router();

router.post('/',function(req, res) {

con.connect(function(err) {
var query = "Select * From user Where email=? AND password=?";
var table = [req.body.email,req.body.password ];
console.log(req.body);

query = mysql.format(query, table);
con.query(query, function (err, rows) {
if (err) {
res.json({ "Error": true, "Message": "Error executing MySQL query" });
} else if(rows!=0) {
res.json({ "Error": false, "Message": "Success","Users": rows });
} else {
res.json({ "Error": true,});
}
});
});
});

app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);

Node 工作正常,但是当我执行命令 url 时,我遇到错误。

最佳答案

确保根据您的请求将 Content-Type header 设置为 application/jsonapplication/x-www-form-urlencoded 因为您的应用程序支持其中任何一个。如果没有具有这些值之一的 Content-Type header ,body-parser 将不会读取请求正文,并且 res.body 将是 未定义

使用 Content-Type: application/json 的 POST 请求示例

const {request} = require('http')

const requestBody = {email: 'abc@gmail.com', password: 'abcdef123456'}

const jsonPostRequest = request({
method: 'POST',
host: 'localhost',
port: 8080,
path: '/api/',
headers: {'Content-Type': 'application/json'}
}, res => {
let chunks = ''
// Handle Response Chunk
res.on('data', chunk => (chunks += chunk))

// Handle Response Ended, print response body
res.on('end', () => console.log(chunks))
})

jsonPostRequest.write(requestBody)
jsonPostRequest.end()

关于mysql - Nodejs : Post method url body parser shows undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com