[英]What is the best way to enable CORS in React Application?
There are different ways to make a REST call in react- eg 在react中有多种方式进行REST调用-例如
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR 要么
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS. 启用CORS的最有效方法是什么。 Is there any other way that I can do this either in frontend or backend?
我还有其他方法可以在前端还是后端执行此操作?
It depends on what HTTP library you are using. 这取决于您使用的HTTP库。
See What is difference between Axios and Fetch? 请参阅Axios和Fetch有什么区别? .
。
I usually use Axios, next what i do is creating a global instance and configuring Axios once. 我通常使用Axios,接下来要做的是创建一个全局实例并配置一次Axios。
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application. 另外,我还在服务器端应用程序上启用CORS。
Thanks to @henrik123 for good explanation: 感谢@ henrik123提供了很好的解释:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at.
浏览器将看到某些Javascript请求试图向与当前浏览器不同的域,子域或端口发起请求。 If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library
如果这些内容中有任何不同,则会启动CORS。使用Axios,Fetch或其他任何库都没关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.