2

what is the correct way to use NodeJs with React?

Currently what I am doing is running Node on port 3000 and React on port 3001

Now, I my Node I have this route

app.get("/", (req, res) => {
  console.log(req.user)
 res.json(req.user)
})

Here console.log shows user details when I manually go to localhost:3000 but If I make an axios request from my react to the above given url it shows undefined.

  componentWillMount() {
             axios.get("http://localhost:3000/").then(response => {
                 console.log(response)
             }).catch(error => {
                 console.log(error)
             })
        }

Now, The req.user is something which were getting from passport google Stratergy and I since the log from localhost:3000 shows the data and the log from localhost:3001 does not show data.

I am confused if I am using the node correct way? i.e sending in request via axios and getting data via res.json

Also, since most of the tutorial or the tutorial I followed used EJS instead of React where user mostly did res.render

I just wanted to know the equivalence of res.render for react in NodeJS

[Update:] I am enabling cross origin resource sharing via plugin in google chrome

14
  • You are making a cross origin request (CORS), port 3001 vs 3000. If you inspect console in Chrome it will show you the warning that data will be clreared before returing it to you. Commented Oct 25, 2018 at 19:00
  • @croraf I am enabling cross origin resource sharing via plugin in google chrome Commented Oct 25, 2018 at 19:01
  • You are using it correctly. In fact this has nothing to do with React. You are just missing something regarding CORS. I had the same issue lately, when the data returned in browser was set to undefined, while node was sending the correct data. Are you using koa in node? Commented Oct 25, 2018 at 19:05
  • Do you use create-react-app ? Commented Oct 25, 2018 at 19:07
  • @croraf Nope. Googling koa Commented Oct 25, 2018 at 19:08

2 Answers 2

3

EDIT: In discussion with OP I found out that this is most likely a passport authentication middleware related issue. Original answer follows.


Looks like a CORS issue, as your frontend providing server is on port 3001, and backend on 3000. I can show you the way I'm using it (in react+node CORS setup, although the issue has nothing to do with React) and I have no CORS issues:

On frontend I use native browser's fetch:

const fetchRelative = async (path, options) => {

    const url = new URL('http://localhost:3000/' + path);

    return await ((await fetch(url, options)).json());
};

Here async/await syntax is used. I'm using babel for transpile, but maybe browsers support that natively.

Options provided to fetch are for example:

{
  method: 'POST',
  body: JSON.stringify(order),
  headers: {
    'Content-Type': 'application/json',
     'Accept': 'application/json'
  }
};

For a simple get request you can leave the options parameter empty.


On backend (node+koa server) I use this:

const Koa = require('koa');
const koaBody = require('koa-body');
const cors = require('koa-cors');

const startServer = (port) => {

    const server = new Koa();

    server.use(cors({ origin: '*', allowMethods: ['GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'] }));

    server.use(koaBody());    
    
    server.use(bindRoutes());
    
    server.listen(port);
};

Basically the same is for express server (https://expressjs.com/en/resources/middleware/cors.html).

bindRoutes is just koa-router configuration extracted in a separate file:

const Router = require('koa-router');
const bindRoutes = () => {
    const router = new Router();

    router.get('restaurants', async (ctx) => {
        ctx.body = 'abc;
    });

    return router.routes();
};

CORS plugin is not used here.

P.S.

async/await explaination and Browser support status https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

fetch explaination and Browser support status https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for answering, I am reading about koa Also, Instead of Fetch I am using axios and since axios returns promise, I think I might not need async?
0

You can run both your Node server and React app on different ports and proxy the React app back to your Node server. This can be done without a CORS plugin. More details on how to set this up is here: https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0

1 Comment

Daveskull thanks for answering, read that article and tried but my "proxy": "localhost:3000" doesn't seem to be working. It sends a request to localhost:3001 instead of "localhost:3000" You can fork and try my git repo: github.com/irohitb/goodED

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.