Alwaysblue
Alwaysblue

Reputation: 11830

Using NodeJs with React

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

Upvotes: 2

Views: 624

Answers (2)

croraf
croraf

Reputation: 4720

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

Upvotes: 3

daveskull81
daveskull81

Reputation: 637

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

Upvotes: 0

Related Questions