我想使用url post params来执行mysql查询。当我通过邮递员发帖时,我在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时,我遇到了错误。
答案 0 :(得分:0)
请确保您的请求已将Content-Type
标题设置为application/json
或application/x-www-form-urlencoded
,因为您的应用支持。如果Content-Type
标头中没有任何一个body-parser
,则无法读取请求正文,而res.body
将会undefined
。
Content-Type: application/json
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()