0

I am trying to call a JSON resource from a URL (on a Node.Js) environment from a React JS project. My attempts so far fail or return nothing.

The Resource API

/* GET users listing. */
app.get('/', function (req, res, next) {
    // res.send('respond with a resource');
    res.json([{
        id: 1,
        name: "Hiccup",
        password: 'hiccup'
    }, {
        id: 2,
        name: "King Arthur",
        password: 'king-arthur'
    }]);
});  

React JS

componentDidMount() {
    let url = 'http://localhost:4000/';

    const myHeaders = new Headers();

    fetch(url, {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors',
        cache: 'default',
        credentials: 'omit',
        headers: {
            'Content-Type': 'application/json'
            },
        })
    .then(res => {
        if (!res.ok) {
            throw new Error('Network response was not ok');
        }

        return res.json();
    })
    .then(data => {
        this.setState({ revData: data })
    })
    .catch(err => this.setState({ revData: err }));
}  

This gives an error:

Access to fetch at 'http://localhost:4000/' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
:4000/:1 

Failed to load resource: net::ERR_FAILED  

Changing mode: 'cors', to mode: 'no-cors' doesn't help.

What am I missing? How should I be going on about it?

Thank you all in advance.

2
  • 1
    Are you using Express for the Node.js server? If so, you can try using the express-cors module to avoid having to set the headers manually. Commented Apr 24, 2020 at 1:03
  • 1
    In fact, it may be applied to both Connect and Express, as said in the docs. Commented Apr 24, 2020 at 1:09

1 Answer 1

1

try :

npm install cors --save

and just add these lines in your main file where your request is going.

const cors = require('cors');
const express = require('express');
let app = express();
app.use(cors());
app.options('*', cors());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.