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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵