Can't load local files when using NodeJS server

前端 未结 2 729
盖世英雄少女心
盖世英雄少女心 2020-12-22 10:41

I\'m very new to NodeJS, and I\'m currently playing around with it (and websockets), so this question might be a bit dumb. Anyway, I\'m following a tutorial which has given

2条回答
  •  时光说笑
    2020-12-22 11:26

    A web server in node.js does not serve ANY files by default (unlike some other web servers). So, if you want js files to be served, you have to define a web server route that will serve them. The code you show returns index.html for all incoming requests coming into that http server so, it should be no surpise that when a request comes in for /js/script.js, your web server sends out index.html.

    A typical framework to use with node.js for web serving is Express and it has express.static() that can be used to define a route that will cover all your static files or all files in a particular directory. You could, of course, code your own static file handling or find some other module to do that also. The point is that you have to write or configure some code to serve your static resource files. That is not done for you automatically by the node.js http server.

提交回复
热议问题