如何解决React和Express在不同的localhost端口上运行,但CORS不会阻止fetch调用
我试图理解为什么CORS不会阻止Axios的get呼叫。详细信息如下:
React running on: localhost:3000
Express running on: localhost:3001
快递代码:
const express = require('express');
const app = express();
app.get('/test',((req,res) =>{
return res.json({data: "hello world"})
} ));
app.listen(5000,() => {
console.log(`Example app listening at http://localhost: 5000`)
})
响应前端代码以使呼叫生效:
function App() {
useEffect(() => {
//______________________ CALL ___________
axios.get('http://localhost:5000/test').then(res => console.log(res.data))
// Able to see the data returned by the server in the console
})
return (
<div className="App">
<h1> TESTING REQUEST </h1>
</div>
);
}
解决方法
在这里它不会受到限制,因为两个请求都将发送到本地主机(源相同)。基本上,从那里开始反应的终点的起点与快递相同。
An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json.
在此处查看更多详细信息,https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
如果您想使其工作。 您可以像这样显式启用CORS
const cors = require('cors')
app.use(cors()) // this will Enable All CORS Requests
您可以通过传递这样的配置对象来配置主机
var corsOptions = {
origin: 'http://example.com',}
app.get('/products/:id',cors(corsOptions),function (req,res,next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
了解更多详情 https://expressjs.com/en/resources/middleware/cors.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。