簡體   English   中英

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

[英]What is the best way to enable CORS in React Application?

在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)
          })
        }

要么

 fetch('http://localhost:8080/feedbacks/addfeedback', {
               method: 'post',
               headers: {
                   'Content-Type': 'application/json',
                   'Access-Control-Allow-Origin' : '*'
               },
               body:body

啟用CORS的最有效方法是什么。 我還有其他方法可以在前端還是后端執行此操作?

這取決於您使用的HTTP庫。

請參閱Axios和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或其他任何庫都沒關系

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM