How do I serve static files through Node.js locally?

前端 未结 3 968
你的背包
你的背包 2020-12-31 08:40

I have the following file locations :

file:///Users/MyName/Developer/sitename/scripts (contains all .js files..)
file:///Users/MyName/Developer/sitename/css          


        
3条回答
  •  感动是毒
    2020-12-31 09:21

    You're able to load the files using the file:// URL because it's a feature of your web browser.

    When loading the address http://localhost:8080 you're no longer leveraging the browser's ability to serve the files (you're accessing the Node.js server). The HTML page being served contains relative paths which work in conjunction with the current hostname to load the assets.

    There is a multitude of options for serving the assets.

    You could serve the files with Node.js:

    • Express.js has a module for serving static assets
    • Node-static is a module I found with a quick search on npm

    Alternatively you could use a web server to serve the files for you. This is likely to be the most performant option. Here is an example of serving static content with nginx.

提交回复
热议问题