【发布时间】:2021-10-11 02:06:30
【问题描述】:
我不知道为什么,但我对 Nodejs 的一种行为感到困惑。
以下是我的 nodejs 代码 my server is running at port:8080
const express = require("express");
const app = express();
const multer = require("multer");
const cors = require('cors');
app.use(cors({
origin:"http://localhost:4000"
}))
app.get("/userinfo", async (req, res) => {
console.log("reached heree");
res.json({
message: "access",
});
});
app.listen(
8080,
(error) => {
if (error) {
console.log("error");
}
},
() => {
console.log("listening at port 8080");
}
);
我正在尝试从不同的来源访问 API [localhost:3000]
import logo from './logo.svg';
import './App.css';
import axios from "axios";
function App() {
const makeRequest =()=>{
axios.get("http://localhost:8080/userinfo").then(response=>{
console.log(response);
}).catch((e)=>{
console.log(e);
})
}
return (
<div className="App">
<button onClick={makeRequest}>Click</button>
</div>
);
}
export default App;
但是当我在检查代码时单击Click 时,我收到了预期的错误消息You are blocked by CORS policy。但是当我在服务器端的终端中看到时,我看到了输出Reached here。
在这一点上,我同时感到困惑和沮丧。跨站请求如何从不同来源触发/userinfo?。我认为这不应该发生。
我该如何解决这个问题??
【问题讨论】:
-
如果您的客户端在 3000 端口上运行,为什么会有此代码
app.use(cors({ origin:"http://localhost:4000"}))? -
是的,我被 CORS 策略阻止了,但是为什么“/userinfo”尽管被 CORS 阻止却在服务器上执行了。
-
因为 CORS 阻止客户端读取响应 - 它不会阻止客户端发出请求。因为有“不透明响应”这样的概念——即客户端不需要访问响应的 CORS 请求
-
@SundarGautam 阅读上面的评论 - CORS 没有做你认为它做的事情:p
-
我只是解释说这与 CORS 无关 - 您需要一些其他方法来确定请求来自哪里 - 无论如何都可以很容易地被欺骗 - 即不容易,但仍然没有什么可做的使用 CORS
标签: javascript node.js reactjs ajax api