【问题标题】:Express App Post RequestExpress 应用程序发布请求
【发布时间】:2017-03-09 04:45:52
【问题描述】:

我在向我的 express 应用发出 POST 请求时遇到了一个奇怪的问题。

我已经使用 Postman 测试了 API,但是当我从 Postman 复制 AJAX 或 XHR 的请求代码时,请求失败并且快递应用返回未定义的快递正文。

网站上的控制台显示以下内容:

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

请求看起来像这样(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);
});

为什么这可以在 Postman 和使用 Curl 的控制台中工作,而不是来自 Web 文档?

【问题讨论】:

  • 我也启用了 Cors,所以应该不是问题。
  • 正如这个答案所暗示的,将响应类型设置为 text/html:stackoverflow.com/a/7053252/1373554
  • 你会如何在快递应用@gjegadesh 中做到这一点?
  • 您的内容类型值与您的数据不匹配。几乎从不需要跨域。 async 的默认值为 true。别再往墙上扔意大利面了。

标签: javascript jquery ajax node.js


【解决方案1】:

当您尝试创建跨域 ajax 时,jQuery 首先发出 OPTIONS 请求而不使用 POST 有效负载,并期望发送以下标头作为响应:

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

要在 Express 中设置响应标头,您可以在开头的某处执行以下中间件(另请参阅 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();
    }
});

另外this关于在 express 上启用 CORS 的帖子可能会有用。

要了解为什么在这种情况下发送 OPTIONS,您可以阅读this 问题的答案。

这是第一个可能的原因,你得到空的身体。

还可以尝试将content-type 更改为contentType(如jQuery docs)并在数据中传递一个字符串

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

【讨论】:

  • 感谢@Vadim - 如何在 express 应用中设置响应标头?
  • 仍然收到“资源解释为文档,但使用 MIME 类型 application/json 传输”@Vadim - 感谢您的编辑
【解决方案2】:

您应该像这样将响应类型设置为 text/html,例如:

app.post("/route", function(req, res) {
    ...
    res.set('Content-Type', 'text/html'); // or 'text/plain', etc.
    ...
    res.send();
});

【讨论】:

    猜你喜欢
    • 2020-05-31
    • 2019-06-21
    • 1970-01-01
    • 2016-07-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多