weixin_33725807 2016-10-26 17:34 采纳率: 0%
浏览 52

Express App发布请求

I am having an odd issue making a POST request to my express app.

I have tested the API using Postman however when I copy the request code from Postman either the AJAX or XHR the request fails and the express app returns an undefined express body.

The console on the site spits out the following:

Resource interpreted as Document but transferred with MIME type application/json

The request looks like this (AJAX):

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://thedomainhere.com/hello",
  "method": "POST",
  "headers": {
    "content-type": "application/json",
    "cache-control": "no-cache",
    "postman-token": "0158785a-7ff5-f6a3-54ba-8dfc152976fc"
  },
  "data": {
    "senderEmail": "hello@hello.com"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

Why would this work on Postman and in the console using Curl, but not from a web document?

  • 写回答

2条回答 默认 最新

  • ℙℕℤℝ 2016-10-26 18:03
    关注

    jQuery first makes OPTIONS request without POST payload, when you try to make cross-origin ajax, and expects the following headers to be sent in response:

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Methods: POST
    Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
    

    To set headers on response in Express you can do the following middleware somewhere in the beginning (also see NodeJS docs for setHeader):

    app.use(function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'POST');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        if(req.method == 'OPTIONS') {
            res.end();
        } else {
            next();
        }
    });
    

    Also this post about enabling CORS on express may be useful.

    To understand why OPTIONS is sent in this case, you can read an answer to this question.

    That's the first possible reason, why you get empty body.

    Also try to change content-type to contentType (as in jQuery docs) and pass a string in the data

    data: JSON.stringify({
        "senderEmail": "hello@hello.com"
    })
    
    评论

报告相同问题?