2

I am playing around with React and Node.js/Express separately. There are two files:

  1. React (build into HTML/JS) file
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  1. Node.js/Express back-end (with the essential npm installed)
var express = require('express');
var app = express();

They work independently but now I am trying to connect the two so the back-end can serve static files to the front-end. I have been searching the web for instructions but most of them are using create-react-app to have the React App set up, which is not my intention since I am simply using React for javascript editing (for now).

Any help on connecting the two? Do I need to install more npm for this to work? Thanks.

2 Answers 2

1

You can serve static files by the express server itself. Put your js and html into a directory name public and tell express to serve static files from this directory :

public/
   index.html
   app.js
index.js  // NodeJs
const app = express();

app.use(express.static('public'));
Sign up to request clarification or add additional context in comments.

1 Comment

By doing app.use(express.static(path.join(__dirname, 'public'))); and app.all('', (req, res) => {res.sendFile(path.join(__dirname, "/public/index.html"));});, I am able to connect them all. Thanks!
0

create-react-app for react is developer-friendly and immediately helps the team to build an app.

There are now certain things you need to take care of now.
1.create webpack file for building the react files and outputting it to a folder. follow this article
2.Serve this output folder to express, follow this article

Comments

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.