javascript时Node.js HTML页面错误404 [英] Node.js HTML page error 404 while getting javascript
问题描述
我正在使用node.js,我希望我的HTML文件能够获取javascript文件.
这是我正在与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');
});
为托管index.html
编写的非常简单的代码.该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>
问题是当我运行server.js
并转到浏览器时,我在控制台上收到此错误:
GET http://localhost:3000/A.js
GET http://localhost:3000/B.js
GET http://localhost:3000/C.js 404 (Not Found)
文件都在同一个目录中,我不明白为什么它没有脚本.
您的server.js
除了对根页面的请求外,不知道如何处理其他任何内容. (即使 http://localhost:3000/index.html 也会失败,并显示404.)>
添加 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');
});
现在,public
文件夹中的所有文件都将按预期提供. (将* .js文件移动到名为public
的子文件夹中)
有关以下内容的良好交互示例,请参见 HyperDev默认项目模板.行动.
Im working with node.js and I wanted my HTML file to GET javascript files.
This is the file i'm running with node.js called 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
. This HTML file has some script tags:
<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:
GET http://localhost:3000/A.js
GET http://localhost:3000/B.js
GET http://localhost:3000/C.js 404 (Not Found)
The files are all in the same directory and I don't understand why it doesn't get the scripts.
Your server.js
does not know how to handle anything besides requests for the root page. (Even http://localhost:3000/index.html will fail with a 404.)
Add the express.static
middleware to serve files from a directory:
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. (Move your *.js files to a sub-folder named public
)
See the HyperDev default project template for a good interactive example of this in action.
这篇关于javascript时Node.js HTML页面错误404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!