Matt
Matt

Reputation: 361

Express CORS response

I am using express to return an api response retrieved via a request call.

router.post('/', function(req, res){

   var options = {
      ...
   }

   rp(options)
        .then(function (parsedBody) {
            console.log(parsedBody); 
            res.json(parsedBody)
        })

The console log displays the expected payload, also when I use Postman I also see the expected payload.

When though my client app gets the response it is:

Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}

Ive tried adding CORS middleware:

app.use(function(request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", 
                    "Origin, X-Rquested-With, Content-Type, Accept");
    next();
});

My client is a very simple react app using fetch:

fetch('http://localhost:3001/api/', {
    method: 'POST',
    dataType: 'JSON',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: data,
}).then((response) => {
      console.log(response);
   }).catch((response) => {
          console.log('Error');
   });

My react app is localhost:3000 and the express api localhost:3001, the expected payload is a very simple object...

{
    athlete: {
        firstname: "Matt"
        ...
    }
}

How can I just forward on the api request response to the clients fetch success method?

Upvotes: 1

Views: 2357

Answers (1)

Matt
Matt

Reputation: 361

The problem is not CORS related, the response within the react app needed parsing as json:

.then((response) => {
    console.log(response.json());
})

Upvotes: 2

Related Questions