【问题标题】:Fetch API Post method is not workingFetch API Post 方法不起作用
【发布时间】:2018-02-16 21:01:06
【问题描述】:
fetch('http://localhost:9000/api/app/contact', {
    method: 'POST',
    headers: {
        'content-type': 'application/json'
    },
    body: JSON.stringify({
        email: this.state.email,
        contactNumber: this.state.phone,
        enquiry: this.state.msg
    })
})
.then(function(res) { return res.json() })
.then(function(data) {
    alert('We will contact you shortly') 
});

当我渲染上面的代码时,我遇到了以下错误:

未能加载http://localhost:9000/api/app/contact:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:8080” 使用权。如果不透明的响应满足您的需求,请设置请求的 模式为“no-cors”以获取禁用 CORS 的资源。

但是当我尝试使用邮递员时,它可以成功运行。请帮助我,我的 fetch api 中是否缺少任何代码。

以下是邮递员 POST 请求和代码。

以下代码是来自Postman的发布请求。

var data = JSON.stringify({
  "email": "test@gmail.com",
  "contactNumber": "0123456789",
  "enquiry": "Testing"
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:9000/api/app/contact");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "d5e08b69-5f0f-8193-e021-e2c3b1bfe1a3");

xhr.send(data);

在 NodeJS 服务器端,我已经在后端使用了 CORS。

var express = require('express'),
    controller = require('./app.controller'),
    router = express.Router(),
    cors = require('cors');

var issue2options = {
  origin: true,
  methods: ['POST'],
  credentials: true,
  maxAge: 3600
};

router.post('/contact', cors(issue2options), controller.sendContactForm);
module.exports = router;

【问题讨论】:

  • 需要在http://localhost:9000 上运行的服务器上添加/启用CORS 支持。见enable-cors.org/server.htmldeveloper.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  • @sideshowbarker 我已经编辑了答案并在节点中配置了 CORS。
  • 我是否正确阅读了您的代码,在节点服务器上您只为 /contact 路由启用了 CORS,但您的前端代码正在向 /api/app/contact 发出请求?在节点后端,那些最终以某种方式解决了相同的路由吗?为了隔离/解决问题,您是否尝试过为所有路由临时启用 CORS 进行测试,而不仅仅是一条路由?

标签: javascript node.js cors fetch-api preflight


【解决方案1】:

您需要为浏览器自行发送的CORS preflights 添加显式OPTIONS 处理:

app.options('/contact', cors(issue2options)); // enable preflight OPTIONS
router.post('/contact', cors(issue2options), controller.sendContactForm);

https://www.npmjs.com/package/cors#enabling-cors-pre-flight

【讨论】:

    【解决方案2】:

    Postman 和浏览器不一样。

    要解决这个问题,您需要服务器 http://localhost:9000/api/app/contact 在其标头中返回 CORS 标头,例如 Access-Control-Allow-Origin: *

    阅读此处了解详细的 CORS 参考 https://enable-cors.org/server.html

    【讨论】:

    • 我已经编辑了我的答案,并且已经在 NodeJS 中配置了 CORS。
    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2023-04-04
    • 2017-08-27
    • 1970-01-01
    • 2018-02-24
    相关资源
    最近更新 更多