在ReactJ上使用Fetch函数时如何处理CORS策略
需要帮助j。我仍在学习ReactJs从PHP后端获取数据。我正在使用XAMPP作为本地服务器。但是,当我在ReactJ上集成Fetch函数时,我会出现CORS策略错误。
这是我的app.jsx上的
useEffect(() => {
fetch("http://localhost:81/opencart/index.php?route=api/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ id: "xl-tshirt" }] }),
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
。
"proxy": "http://localhost:81/"
代码
访问'http:// localhost:81/opencart/index.php?route = api/create'rient'http:// localhost:3000'已被CORS策略阻止无法传递访问控制检查:没有“访问控制”标题在请求的资源上。如果不透明的响应满足您的需求,请将请求模式设置为“无库”,以通过禁用CORS来获取资源。
我该如何解决?
need help for ReactJs. I still learning reactJs to fetch data from PHP backend. I'm using Xampp as my local server. but when i integrate fetch function on ReactJs, i got CORS policy error.
here is my code from on my App.jsx
useEffect(() => {
fetch("http://localhost:81/opencart/index.php?route=api/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ id: "xl-tshirt" }] }),
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);
On my reactJs package.json file i added this
"proxy": "http://localhost:81/"
but still display error on browser console
Access to fetch at 'http://localhost:81/opencart/index.php?route=api/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
How do I resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
cors 问题肯定来自服务器。因此,理想的方法是将服务器设置为从交叉原点接受您的请求。
似乎您正在使用使用PHP构建的服务器,然后检查后端服务器以添加
CORS
配置。对于Express.js和其他人来说,添加了几种方法,例如添加“ CORS”中间件。
CORS issue is definitely coming from Server. So the ideal way is to set your server to accept your request from cross origin.
Seems you are working with server built with PHP, then check your backend server to add
CORS
configuration.For Express.js and others are having several way to add it such as adding 'cors` middleware.