How to allow cors on nodeJS server

Issue

I have a super simple backend with node.js, and I have CORS enabled. However, I still can’t get to allow sending any kind of data cross-origin.

This is my backend running on port 3000:

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

const app = express();

var corsOptions = {
    origin: 'http://127.0.0.1:3001',
    optionsSuccessStatus: 200 // For legacy browser support
}

app.use(cors(corsOptions));

//app.use(cors()); ALSO TRIED THIS

app.listen('3000', () => {
    console.log('Listening on port 3000');
});


app.get('/number', (req, res) => {
    res.json({number: 1});
});

And this is how I fetch from frontend, running on port 3001:

fetch('http://localhost:3000/number')
    .then(res => console.log(res));

But this is the response I’m getting:

Response {
    body: ReadableStream
    bodyUsed: false
    headers: Headers {}
    ok: true
    redirected: false
    status: 200
    statusText: "OK"
    type: "cors"
    url: "http://localhost:3000/number"
}

But I was expecting:

Response {
    number:1
}

I think this is mainly a CORS issue, because everything works just fine when using postman.

Thank you so much for your time!

Solution

This is not the cors issue, simply change your fetch like a blow to get the expected result.

fetch('http://localhost:3000/number')
    .then(res => res.json()).then(data=>console.log(data));

this will give you {number: 1} as a result.

Answered By – Yasir Ali

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.