【发布时间】: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.html 和developer.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