[英]Getting request.body value undefined in nodejs?
my front end code: 我的前端代码:
console.log('In front end ', UserDetails.fname);
$.ajax({
type: 'POST',
data: UserDetails.fname,
url: 'http://localhost:3000',
success: function(data){
console.log('Success!!');
},
error: function(error){
console.log('Error!!');
}
})
In first console line the UserDetails.fname
printing correctly. 在第一个控制台行中, UserDetails.fname
正确打印。 But when I send it to the back end, the back end shows it as undefined
. 但是,当我将其发送到后端时,后端将其显示为undefined
。
my back end code 我的后端代码
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var userId = 1;
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'facebook'
});
conn.connect(function(err){
if(!err){
console.log('Database connection success...');
} else {
console.log('Failed to connect to database...')
}
});
var app = express();
// Add headers
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
app.use(bodyParser.text({ type: 'text/html' }));
app.post("/", function(req, res){
console.log(req.headers);
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(3000);
I have updated my code. 我已经更新了我的代码。 But still I have the same probelm. 但是我仍然有同样的想法。
Make sure to put your
body-parser
code above all the routes 确保将body-parser
代码放在所有路线之上
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Did you setup a body parser in express ? 您是否在Express中设置了正文解析器?
https://github.com/expressjs/body-parser#user-content-change-accepted-type-for-parsers https://github.com/expressjs/body-parser#user-content-change-accepted-type-for-parsers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.