NodeJS + Express served HTML file not loading js file?

后端 未结 2 626
不思量自难忘°
不思量自难忘° 2021-01-02 01:06

I am running a NodeJS server which uses a catchall route to serve a file \'index.html\'. In that file, I am linking to a javascript file in the same directory. That javasc

相关标签:
2条回答
  • 2021-01-02 01:44

    You should set your static folder like this

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

    Also, your html file will look inside the /public folder itself for your script file. You'll need to give your index.html file the right path to your script file.

    <script src="/app/views/test.js"></script>
    
    0 讨论(0)
  • 2021-01-02 02:03

    Here's what's happening:

    • The browser requests /, which is responded to by your catchall route, so it gets back index.html.

    • The browser then sees a script in the html at ./test.js, so the browser then interprets that as /test.js and makes a request for that. The express.static middleware looks up public/test.js, which does not exist, so it passes execution to the next defined route that matches the request, which is your catchall route. This means html is sent for the javascript file, hence the error that you see.

    So to fix this, you need to change ./test.js to the actual relative path (./app/views/test.js) or use an absolute path (/app/views/test.js) to make sure the correct path is always used, no matter what the current path is.

    Additionally, you will need to change this:

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

    to something like this:

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

    Otherwise the express.static middleware will look for a directory named public off the root of your filesystem and you will have the same problem with the catchall route serving html for your javascript file request.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题