Fetch API Post 方法无效

Fetch API Post method is not working

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') 
});

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

Failed to load http://localhost:9000/api/app/contact: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

但是当我尝试使用邮递员时,它成功地工作了。请帮助我,我的提取中是否缺少任何代码 api。

以下是邮递员[=3​​1=]请求和代码。

以下代码是 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;

Postman跟浏览器不一样

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

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

您需要为浏览器自己发送的 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