我的前端代碼:在nodejs中獲取request.body值undefined?
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!!');
}
})
在第一控制檯線路的UserDetails.fname
打印正確。但是當我將它發送到後端時,後端將其顯示爲undefined
。
我的後端代碼
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);
我已經更新了我的代碼。但我仍然有同樣的問題。
這將是更有幫助,如果您發佈完整的後端代碼 –