我只是对nodeJs app中的某个方法进行ajax调用,并希望记录所有参数以正确查看传递数据。但是因为我发布它不是..
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// set the port of our application
var port = process.env.PORT || 8080;
app.set('view engine', 'ejs');
// make express look in the public directory for assets (css/js/img)
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/', function(req, res) {
// ejs render automatically looks in the views folder
res.render('index');
});
app.listen(port, function() {
console.log('Our app is running on http://localhost:' + port);
});
'use strict';
app.post('/sendMail', function(request, response) {
console.log(request.body)//returns {} but why its empty?
})
这里是ajax调用;(我通过开发控制台验证参数存在于标题中)
constructor() {
this.message={
email:"",
message:""
}
}
@action postData() {
$.ajax({
url:"http://localhost:8080/sendMail",
ContentType:'application/json',
dataType:'json',
type:'post',
data:{body:this.message},
success:(result) =>{
},
编辑:如果我通过POSTMAN发帖请求,我能够在日志中看到数据我选择内容类型:application / json并添加了原始json字符串“{'message':'hello world'}”我看到了在nodejs中记录它成功通过了我的ajax调用错误吗?
答案 0 :(得分:2)
它是空的,因为你指定请求的使用应该包含一个JSON主体,但实际上不发送JSON,你发送一个对象。
在您的ajax请求中,更改此行
data:{body:this.message}
到
data: JSON.stringify(this.message)