我有一个start_express.js
文件,我用node:
const express = require("express");
const app = express(),
DEFAULT_PORT = 5000
app.set("port", process.env.PORT || DEFAULT_PORT);
app.get("/whatever", function (req, res) {
res.send("It works!");
console.log("Something's wrong");
});
var server = app.listen(app.get("port"));
我的反应应用程序,我有一个handleSubmit
方法试图获得响应:
handleSubmit(event) {
axios.get('http://127.0.0.1:5000/whatever')
.then(function (response) {
alert(response);
})
.catch(function (error) {
console.log(error);
});
event.preventDefault();
}
当我点击提交时,start_express服务器会输出“Something's wrong”,但客户端上的提醒永远不会有效。它给了我以下错误:
Failed to load http://127.0.0.1:5000/whatever: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
如果我无法回复,我该如何向客户发送请求?
答案 0 :(得分:1)
您正在从端口3000 http://localhost:3000
为该站点提供服务,因此浏览器正在保护您不要访问不允许交叉起源的站点。
简单启用快速docs
的CORS出于安全原因,您甚至可以在开发期间启用CORS
if (process.env.NODE_ENV !== 'production) {
app.use(cors())
}
答案 1 :(得分:1)
是的,令人困惑。但正如错误消息所示,您需要在服务器上设置Access-Control标头。客户端部分很好。使用express最简单的方法可能是使用cors包:
$ npm install cors
这样您就可以进行所有访问 - 您可能只想进行测试:
const express = require("express");
const cors = require('cors');
const app = express(),
DEFAULT_PORT = 5000
app.use(cors());
...
请在此处查看好文档:https://github.com/expressjs/cors