零零乙 2017-08-06 11:13 采纳率: 33.3%
浏览 60

Node.js发布空对象

I simply make a ajax call to certain method in nodeJs app, and expected to log all parameters to see pass data properly. but since I post this its not..

 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? 
})

and here is ajax call;(I validate paramters exist in headers via dev console)

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) =>{
  },

EDITED: I am able to see data in log if I make a post request via POSTMAN I choose content-type:application/json and added raw json string "{'message':'hello world'}" and I saw in nodejs log its passed successfully whats wrong with my ajax call here ?

  • 写回答

1条回答 默认 最新

  • weixin_33743880 2017-08-06 11:19
    关注

    It's empty because your using specifying the request should contain a JSON body but don't actually send JSON, your sending an object.

    In your ajax request, Change this line

    data:{body:this.message}
    

    to

    data: JSON.stringify(this.message)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题