简体   繁体   中英

Node serving same resources from all paths

I'm using React BrowserHistory for navigation. I want the same files to be served from my Node server regardless of the URL path.

My server code:

const http = require('http');
const path = require('path');
const express = require('express');
const app = express();
const hostname = 'localhost';

app.use(express.static('../public'));

app.get('*', (req, res)=>{
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

const port = process.env.PORT || 8007;
app.listen(port, ()=>{
  console.log('Production Express server running at localhost:' + port)
});

http://localhost:8007 => works fine

http://localhost:8007/help => works fine

http://localhost:8007/help/faq => Fails

I want all URLs to return the same resources, served from ../public . However, it seems that the express.static doesn't work when the resource isn't requested from the root. So, for instance, when the browser asks for <script src="scripts/main.js"></script> , it thinks I want ../public/help/scripts/main.js , whereas I actually want ../public/scripts/main.js/ . So, because express doesn't find such file, it moves on to the app.get('*'... , which returns the ../public/index.html file when the script is requested.

So, the desired behavior is:

  • return the same index.html for any path (with any number of sub-folders), and let React figure out what to show
  • return the resources always relative to the path index.html is served from, not relative to the path in the URL

It works when I use absolute paths in my resource requests (IE <script src="http://localhost:8007/scripts/main.js"></script> ), however writing it like that obviously isn't desirable, because it needs to be changed when it's hosted elsewhere.

What should I do?

you can use that condition for your routing:

app.get('*/**', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'));
});

It's work find for me.

Be carefull with this method, your browser will reload the entire page for each call to a route.

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