修改请参阅下面接受的答案以了解该修复程序。我还必须从POST请求中删除行contentType: 'appliction/json',
。
我正在尝试向Node.js / Express发送字符串,但req.body
未定义为服务器端。
客户端jQuery:
$.post({
traditional: true,
url: '/matches',
contentType: 'appliction/json',
data: viewedProfiles,
dataType: 'json',
success: function(response){
快递:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post('/matches', isLoggedIn, function(req, res){
console.log(req.body) // this is undefined
var loadedProfiles = []
loadedProfiles.push(req.body.viewedProfiles)
console.log('loadedProfiles')
console.log(loadedProfiles)
我试过了:
data: JSON.stringify(viewProfiles)
我可以在开发工具中看到XHR请求,它包含我期待的字符串。
我错过了将数据发送到Express的超级明显的事情吗?
感谢。
答案 0 :(得分:3)
您的服务器端代码看起来很好,但您需要使用$.ajax()
而不是$.post()
函数,因为$.post()
函数将数据发送到url(使用url编码)。所以你的JQuery代码将是
$.ajax({
url: '/matches',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"viewedProfiles": viewedProfiles}),
success: function(response){
我希望这会对你有所帮助
答案 1 :(得分:0)
我已经配置了完全相同的设置。以下代码有效:
var profiles = { 'data' : 'hello' };
$.post({
traditional: true,
url: '/matches',
contentType: 'application/json',
data: JSON.stringify( profiles ),
dataType: 'json',
success: function(response){ console.log( response ); }
} );
我的nodejs引擎:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post( '/matches' , function(req, res){
console.log(req.body) // this outputs: { data: 'hello' }
} );
顺便说一下,你的contentType有一个拼写错误,'应用 A / json'