1

Code:

function App() {

    useEffect(() => {

        axios({
            url: 'http://____/user/list',
            method: 'GET',
            dataType: 'json',
            headers: {
                'Authorization': '______',
            },
        })
        .then( res => {
            console.log('| response |', res)
        })
        .catch( error => {
            console.log('| error |', error);
        })

    }, [])

    return (
        <div></div>
    )
}

Error:

Access to XMLHttpRequest at 'http://___' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I understand I am making an XMLHttpRequest to a different domain than my page is on and that Postman calls "POST" request directly but we send an "OPTIONS" request first. Is the browser or server blocking it for security reasons? Am I missing anything in the client side or server side?

anonym
  • 4,460
  • 12
  • 45
  • 75
  • The API server is not setting the `Access-Control-Allow-Origin` to allow `localhost:3000` to make request to it. If you control the server and it's running locally as well, you could just allow anything with `*`, or if not, you could trick the API server and the browser by changing your computer's host file to point a sub-domain of the API server domain to `127.0.0.1` while you're developing, though it won't work once deployed. – Emile Bergeron Aug 18 '20 at 04:29

1 Answers1

1

The issue is that the domains don't match up, which is against CORS. The server needs to handle OPTIONS requests and reply with the proper headers that signify the request can be made. You'll probably want to add a Access-Control-Allow-Origin response header on the server. You'll also want to handle Access-Control-Allow-Headers. The response from OPTIONS should look something like:

OPTIONS /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type


HTTP/1.1 204 No Content
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Vary: Accept-Encoding, Origin
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive

You can read up more about CORS on MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Kyle
  • 3,935
  • 2
  • 30
  • 44