Program-Me-Rev
Program-Me-Rev

Reputation: 6624

How to call a NodeJs resource from React Js

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.

Upvotes: 0

Views: 116

Answers (1)

Nilanka Manoj
Nilanka Manoj

Reputation: 3728

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());

Upvotes: 1

Related Questions