Search code examples
node.jsreactjsmern

Connecting reactjs with nodejs


I have an app with front end react and backend node. The backend is tested with postman and working fine. the front end ui is tested with static data. Now I have set up a proxy with the react part to connect to the backend node.

My react app is runnning on port 3000 my node is running on port 5000.

When I request a route on my backend from my front end the app does not utilize the proxy set up Instead it gives me a Bad request error.

My front end is in client folder .Please help. the project can be found on the following github link

https://github.com/prashantbhat84/mern-contactkeeper

Please help


Solution

  • It seems to be a cross-origin problem. There are two ways to solve cross-origin problems in node server,

    1. Using cors node module

    First install cors module. npm install cors

    and then use it inside your app

    const Express       = require("express");
    const BodyParser    = require("body-parser");
    const Cors          = require("cors");
    
    const app = Express();
    app.use(Cors());
    
    app.use(BodyParser.urlencoded({ extended: false }));
    app.use(BodyParser.json());
    
    app.listen(3001, 'localhost', (err) => {
        if(err) {
            console.log(err);
            process.exit(-1);
        }
        console.log("Server listen port 8083");
    });
    
    1. simply use following headers
    app.use(function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
        next();
    });