简体   繁体   中英

Serving create-react-app build files on express server

I want to serve build files of my react app on my other express application. So I copied all the static files inside build folder to public folder inside my express application and I used.

app.use(express.static(path.join(__dirname, './public')));

app.get("/",(req,res)=>{
    res.send()}
    )

app.get("/differentRoute",(req,res)=>{
    res.send()}
    )

app.listen(4000)

When I make a get request on http://localhost:4000/ my react page loads perfectly, however when I make the same request on http://localhost:4000/differentRoute , nothing loads, can someone explain me how it works?

When you request / it finds the index.html file in the public directory, and serves it up using the static handler.

Nothing get ever get to the explicit handler for / since the static route always catches it first.

When you request /differentRoute , there is no matching file in the public directory so the explicit route for that is triggered. You call res.send() with no arguments, which doesn't make sense.


If you want to have URL based routing and don't want to use server side rendering, then use the HashRouter .

If you want to have real paths for the different pages in the app, then use server side rendering (eg with Next.js .

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