Node JS 不断收到无法加载资源的错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17775944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:05:46  来源:igfitidea点击:

Node JS keep getting Failed to load resource error message

node.js

提问by methuselah

I am currently testing out a node.js application and have tried to add:

我目前正在测试一个 node.js 应用程序并尝试添加:

<link rel="stylesheet" href="assets/css/formalize.css" />
<script src="assets/js/jquery.formalize.js"></script> 

to my code but keeping getting the error message:

到我的代码,但不断收到错误消息:

Failed to load resource: the server responded with a status of 404 (Not Found) 

http://localhost:3000/assets/css/formalize.css

Failed to load resource: the server responded with a status of 404 (Not Found) 

http://localhost:3000/assets/js/jquery.formalize.js

Any idea where I'm going wrong? Here is my code so far (in app.js)

知道我哪里出错了吗?到目前为止,这是我的代码(在 app.js 中)

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(3000);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.htm');
});

io.sockets.on('connection', function(socket) {
    socket.on('send message', function(data) {
        io.sockets.emit('new message', data);
    });
});

回答by go-oleg

You need to add the express.staticmiddleware to your appand make it point to your directory with static assets.

您需要将express.static中间件添加到您的中间件,app并使其指向您的包含静态资产的目录。

For example, if you directory structure is set up like this:

例如,如果您的目录结构设置如下:

app.js
index.htm
  static
    assets
      js
        jquery.formalize.js
      css
        formalize.css

You would specify your static asset directory like this:

您可以像这样指定静态资产目录:

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

And reference your files in your html file like this:

并在您的 html 文件中引用您的文件,如下所示:

<link rel="stylesheet" href="/assets/css/formalize.css"/>
<script src="/assets/js/jquery.formalize.js"></script>