javascript - mode: 'no-cors' working with fetch but fails for axios - Stack Overflow

I prefer axios over fetch because of its simplicity and ease-of-use. I am running a local dev server wh

I prefer axios over fetch because of its simplicity and ease-of-use. I am running a local dev server which sends AJAX requests to some remote endpoint. The request gets blocked due to the same-origin-policy. So I modified my webpack config like this:

devServer: {
  headers: {
    'Access-Control-Allow-Origin': '*',
  },
},

Now if I use fetch for making API requests, I add "mode": "no-cors" to allow cross origin requests and everything works fine. However, this does not work with axios.

Whereas fetch is based on Request API, which allows specifying mode: "no-cors", axios is based on XHR, which has no support for specifying mode. I can work around the issue by opening an insecure chrome window by running chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security where --user-data-dir is some path of my file system. However, an insecure chrome instance won't allow extensions to run, so I can't use React and Redux DevTools. Here is a snippet that uses fetch and axios to make requests. The fetch call works while axios fails:

ponentDidMount() {
  fetch(someAPIEndpoint, {
    mode: 'no-cors',
  })
  .then(response => console.log(response))
  .catch(error => console.error(error))

  axios
  .get(someAPIEndpoint, {
      mode: 'no-cors',
  })
  .then(results => console.log(results))
  .catch(error => console.error(error))
}

Using a proxy server is not possible in my situation either. Is there any other workaround in code so that i can use axios and bypass this issue. Thanks in advance!!!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745636518a4637428.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信