简体   繁体   English

获取javascript时,Node.js HTML页面错误404

[英]Node.js HTML page error 404 while getting javascript

Im working with node.js and I wanted my HTML file to GET javascript files. 我正在使用node.js,我希望我的HTML文件能够获取javascript文件。

This is the file i'm running with node.js called server.js : 这是我用node.js运行的文件,名为server.js

var app = require('express')();
var http = require('http').Server(app);

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

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Very simple code made to host index.html . 非常简单的代码用于托管index.html This HTML file has some script tags: 此HTML文件包含一些脚本标记:

<script type="text/javascript" src="./A.js"></script>

<script type="text/javascript" src="./B.js"></script>

<script type="text/javascript" src="./C.js"></script>

And the problem is that when i run server.js and I go to the browser I get this errors on the console: 问题是,当我运行server.js并进入浏览器时,我在控制台上遇到了这个错误:

GET http://localhost:3000/A.js 
GET http://localhost:3000/B.js 
GET http://localhost:3000/C.js 404 (Not Found)

404 error not found 找不到404错误

The files are all in the same directory and I don't understand why it doesn't get the scripts. 这些文件都在同一个目录中,我不明白它为什么不能获取脚本。

Try looking at the Express 1 Documentation for serving static files. 尝试查看Express 1文档以提供静态文件。

You're serving your index file with these lines: 您使用以下行为您的索引文件提供服务:

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

You can serve js files the same way or by putting them in a public folder and adding app.use(express.static('public')) . 您可以以相同的方式提供js文件,也可以将它们放在public文件夹中并添加app.use(express.static('public'))

Then you can reference them as public/A.js 然后你可以将它们称为public/A.js

Your server.js does not know how to handle anything besides requests for the root page. 除了对根页面的请求之外,你的server.js不知道如何处理任何事情。 (Even http://localhost:3000/index.html will fail with a 404.) (甚至http:// localhost:3000 / index.html也会因404而失败。)

Add the express.static middleware to serve files from a directory: 添加express.static中间件来提供目录中的文件:

var express = require('express');
var app = express();
var http = require('http').Server(app);

express.static('public')

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

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Now any files in the public folder will be served as you intend. 现在, public文件夹中的所有文件都将按您的意愿提供。 (Move your *.js files to a sub-folder named public ) (将* .js文件移动到名为public的子文件夹)

See the HyperDev default project template for a good interactive example of this in action. 有关此操作的良好交互示例,请参阅HyperDev默认项目模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM