在React Application中启用CORS的最佳方法是什么?

时间:2019-02-26 10:36:31

标签: reactjs rest

在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

启用CORS的最有效方法是什么。 还有其他方法可以在前端还是后端进行?

1 个答案:

答案 0 :(得分:0)

这取决于您使用的HTTP库。

请参见What is difference between Axios and Fetch?

我通常使用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}`;

我还要在服务器端应用程序上启用CORS。

感谢@ henrik123提供了很好的解释:

  

浏览器将发现某些Javascript请求试图向与当前浏览器不同的域,子域或端口发起请求。如果这些都不相同,则会启动CORS。使用Axios,Fetch或其他任何库都没关系

相关问题