1

before anything else, I want to say, that I have read about 12 similar questions on the StackOverflow, but none of them helped me to solve my issue and most of them had pretty unclear answers, so I believe that this question is worth asking, also I'm just a beginner.

Environment:

I have a react app running on localhost on port 3000 and an Express server on port 8000. My server:

const express = require('express');
const app = express();

const port = 8000;

app.post('/register', (req, res) => {
    res.send(JSON.stringify({test: 'HELLO!'}));
});

const server = app.listen(port, () => console.log('Listening on port', server.address().port));

And client:

static register(username, password) {
    return fetch('http://localhost:8000/register', {
      method: 'POST',
      body: JSON.stringify({username, password}),
      headers: {'Content-Type': 'text/plain'}
    }).then(response => console.log(response));
  }

When sending this request I would get this error message:

Failed to load http://localhost:8000/register: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

After some research I tried some solutions: Adding this middleware before "POST" on my server:

app.all('/*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
});

It didn't help, so I've tried node CORS package and still, it didn't solve my issue. But something has changed: I was no longer getting this error message instead, I would get the response logged, but instead of getting an object that I have sent from the server, I was getting some kind of 'error object':

bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:8000/register"

But, when I opened a network tab in Chrome, I saw that the response was what I expected {test: HELLO!}, so Chrome was changing something, so I have disabled Chrome security, but it still was logging the same error object. So after trying all of this, I couldn't make my code work, so can anyone fully answer how to send requests from React app to the express server without getting cors error?

Full server code:

const express = require('express');
const cors = require('cors');
const app = express();

const port = 8000;

app.all('/*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
});

app.post('/register', (req, res) => {
    res.send(JSON.stringify({test: 'HELLO!'}));
});

const server = app.listen(port, () => console.log('Listening on port', server.address().port));
Misho Tek
  • 624
  • 2
  • 11
  • 22
  • 1
    Can you show how were you using the `cors` middleware?, because just with that correctly setup you shouldn't get any CORS related error. That route you have in there is not the right way to set CORS anyway, you usually want to end the request after setting the headers for `OPTIONS` method. – Marcos Casagrande Apr 04 '19 at 19:57
  • I have updated, my question. I've already gotten the answer, but still could you explain, why this is not a right way to set CORS, I have just started learning, so it would be really helpful. – Misho Tek Apr 04 '19 at 20:16

1 Answers1

1

I think that your entire request is working fine..which is why you got status: 200. The problem is how you're handing the request in client. which should be

static register(username, password) {
    return fetch('http://localhost:8000/register', {
      method: 'POST',
      body: JSON.stringify({username, password}),
      headers: {'Content-Type': 'text/plain'}
    })
    .then(response => response.json())
    .then(json => console.log(json));
  }

The 'error object' you mentioned is just the complete response, which contains the json you actually requested, along with some metadata.

ManavM
  • 2,918
  • 2
  • 20
  • 33