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"
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况