简体   繁体   中英

Rendering react with node.js in development

I am (very) new to node.js and I am trying to get a development environment started with React.

const express = require('express')
const mongoose = require('mongoose')
const app = express()

// this displays the index.html file
app.use(express.static(__dirname + '/public'));
// trying to see the app.js
app.get('/',  (req, res) => {
 
  res.render('app')
})



app.listen(process.env.PORT || 5000);

Right now I am simply trying to be able to view my app.js when I run nodemon. But right now it is only showing the index.html file in the public folder. and when I run npm start it renders both the index.html and the app.js.
I am 100% doing something wrong and am not in my element here. Any help/advice would be appreciated.
My full repo is here for viewing here Thank you in advance.

If you want to connect your react js project to the node js

In Development

you simply run their server and start it

In Production

You can use sendFile function coming from express.js to run the frontend

https://dev.to/loujaybee/using-create-react-app-with-express

Your code is simply serving a static HTML file located in the public directory everytime the user make a GET request to the root (in your case, localhost:5000 ). It is not interacting with React yet.

Usually when starting a project with React (frontend) and Node (backend), you would create them as separate projects, in separate repositories. So you could create a React application using a bootstrap such as create-react-app running on PORT 3000 and in another terminal tab, start your NodeJS application in PORT 5000 like in your example. Then, you can call your backend endpoint from your frontend React application, by referencing http://localhost:5000 By doing this, your backend code don't need to serve static files anymore, it can return data such as JSON and make connections to a database for example.

Since your question is not specific enough, you could be talking about server side render. In server side render apps using Node and React, you have a frontend built with React and a Node server that will return the same React code as a string, using the react-dom/server package to help. This is more complex, but basically you will have the same React code on the client AND on the server. There are performance benefits, because the user can see some content rendered right when he enters the page, without having to wait the React bundle (javascript file) to load. If you want to know more about creating a server side render app with React and Node, there is a nice digital ocean tutorial here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM