DEV Community

GreggHume
GreggHume

Posted on • Updated on

Browser: Fetch API Cors settings for server wildcard origin

Cors issues are a pain, especially if your server is allowing all but fetch is still throwing errors. Here is a fix.

fetch(`http://endpoint.com`, {
  method: 'GET', // *GET, POST, PUT, DELETE, etc.
  mode: 'cors', // no-cors, *cors, same-origin
  cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'omit', // include, *same-origin, omit
  headers: {
    'Content-Type': 'application/json'
  },
})
.then((res) => res.json())
.then((data)=> {
  console.log('data', data)
})
Enter fullscreen mode Exit fullscreen mode

Axios might not work in some cors situations:
In a quote from this thread:

It's important to note is that mode, credentials, and crossdomain aren't supported for configuring Axios. The reason why your example works when using fetch is because those options are part of the Request API (docs for mode are here).

Errors you may have seen when making your requests:

"Uncaught (in promise) SyntaxError: Unexpected end of input"

"Access to fetch at '...' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'"

"JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)