Z
Z
zillow2019-07-02 04:43:22
CORS
zillow, 2019-07-02 04:43:22

Why GET request doesn't work in browser, but it works in Postman?

I have a react app built NOT through create-react-app but with webpack config. When I make a fetch request to localhost:8000/api/muggers in my React app (the server is already created with node):

fetch("http://localhost:8000/api/muggers", param)
 	.then(response => response.json())
  	.then(json => console.log(json))


, then this error pops up:
Access to fetch at 'localhost:8000/api/muggers' from origin 'localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource . If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But if I also pass an arguments object to fetch like this:
const param = {
  method: 'GET',
        mode: 'no-cors',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer: token',
    "Access-Control-Allow-Origin" : "*", 
    "Access-Control-Allow-Credentials" : true
  },
};

Then the usual annoying error will change to this:
item.js?2f47:29 Uncaught (in promise) SyntaxError: Unexpected end of input
    at eval (item.js?2f47:29)

pointing me to a piece of code
response.json()
I suffered for a long time and did all sorts of different things. If I use a server for test data - jsonplaceholder.typicode.com - in my application, then everything works fine. But if I use another server for test data - swapi.co, then again everything is the same as described above (an error pops up). But I remember that when I tried swapi.co in my react app created via create-react-app it worked. And if you make a request to the node server in the application through CRA, then everything will be cool again. And maybe it turns out that the problem is in my config, here it is:


So what can I do to avoid errors? And the data came out fine.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-02
@zillou

Read about cross-domain queries.
If using Express, include middleware cors

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question