【发布时间】:2019-12-29 11:21:59
【问题描述】:
我正在开发一个在请求后加载 HTML 页面的简单服务器。
代码工作正常,但我无法将本地资源“连接”到我的 HTML 页面(CSS 和 Javascript 文件),我收到标题中提到的错误。
这是我的 Node.js 服务器:
var server = http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
console.log("Print path:"+ path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '/index.html':
console.log("print full address:"+__dirname + path);
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
response.end();
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
server.listen(5000);
index.html 文件已加载,但我无法访问我的 HTML 文件中的所有本地脚本和样式表。
这是我的 HTML(短版,只是脚本和样式表部分):
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>A Pen by Mattia Surricchio</title>
<link rel='stylesheet' href='02cbe09766a509e291eb2a444.css'>
<link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src='02cbe09766a509e291eb2a444.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/tone/13.8.9/Tone.min.js'></script>
<script src="script.js"></script>
</body>
所有文件都在我的node.js文件的同一个文件夹中,所以服务器、HTML、CSS和Javascript文件都在同一个文件夹中。
我正在浏览器中使用http://localhost:5000/index.html 访问服务器。
我用console.log() 检查了路径,它们看起来是正确的(HTML 加载正确,问题是页面内的 CSS 和 Javascript 文件)。
可能是什么问题?
PS:如果我自己加载index.html 页面(只需用浏览器打开它),所有文件都会加载并正确显示。
编辑:
我部分解决了转移到express.js 的问题,这是我的新服务器(我遵循这个答案:nodejs/express include local js file):
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var path = require('path');
var express = require('express');
app.use(express.static(path.join(__dirname, 'Pad')));
app.get('/', function(req, res) {
res.redirect('index.html');
});
我的目录结构如下:
root/
app.js //this is my node.js server
node-modules
package.json
Pad/
index.html
script.js
style.css
通过这个解决方案,我能够加载 HTML 文件,包括链接在 HTML 文件中的 script.js 文件和 style.css。
但是,我也在使用本地模块(在这种特殊情况下,我使用的是 Tone.js 和 Tonal.js),这些模块是在文件夹 node-modules 中使用 npm 安装的。
我如何访问这些资源?我收到了error 404。
我必须将这些资源移到我的Pad 文件夹中吗?
【问题讨论】:
-
这对于 express.js 来说超级简单。
-
@CloudBranch 我解决了迁移到 express.js 的问题。但是现在我无法访问节点模块,我该如何解决这个问题?
标签: javascript html node.js server