简体   繁体   中英

Serving static files with express for non-root paths

I'm using express to serve a react app (bootstrapped with Create React App). The project has the following file structure:

|--client/
|    |--build/
|    |    |--static/
|    |    |    |--main.css
|    |    |    |--main.js
|    |    |
|    |    |--index.html
|    |
|    |--public/
|    |--src/
|
|--server/
     |--index.js

The build folder contains all of the static files, and I want to serve them from a non-root url. The express server is configured:

app.use('/some_path', express.static(path.resolve(__dirname,'../client/build')));

In my index.html, I initially had .css and .js files with href='/static/main.css and src='/static/main.js which didn't work (404 errors) because I believe the server would try to look for the files under /some_path/static/ for the files and not find them.

When I tried changing the paths in index.html to href='/some_path/static/main.css , I get 200 statuses for all of the requested files (the files sent match the originals), but nothing is rendered on the page. Inspecting the html page shows this in the body:

<div id="root">
    <!-- React empty: 1 -->
</div>

Any idea what I'm doing wrong here? Is there something simple I'm missing or something that needs to be configured when using React Create App?

https://expressjs.com/en/starter/static-files.html

the doc already said the following:

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:

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

for example: have a path as following:

https://localhost:port/product/new

with all the .JS and .CSS file in folder "public", normally, Express will return an error that cannot load the .JS and .CSS file. We only need to include the following line:

app.use('/product', express.static('public'))

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