最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin10PV0评论

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!!!

Post a comment

comment list (0)

  1. No comments so far