【发布时间】:2019-01-27 02:54:28
【问题描述】:
我有一个简单的 node.js 服务器,它旨在使用我的 index.html 文档在地址 http://localhost:3000/hi/ 处响应 GET 请求,但我无法弄清楚它为什么使用 (index) 和索引来读取/响应.js。
我使用路由器对象的功能是:
const http = require('http');
const path = require('path');
const fs = require('fs');
let contacts = {
"1234": {
id: "1234",
phone: "77012345678",
name: "Sauron",
address: "1234 Abc"
},
"4567": {
id: "4567",
phone: "77012345678",
name: "Saruman",
address: "Orthanc, Isengard"
},
};
let loadStatic = (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./index.html', null, (err,data) => {
if (err) {
return console.log('error');
} else {
res.write(data);
}
res.end();
});
}
let routes = [
{
method: 'GET',
url: /^\/contacts\/[0-9]+$/,
run: getContact
},
{
method: 'DELETE',
url: /^\/contacts\/[0-9]+$/,
run: deleteContact
},
{
method: 'GET',
url: /^\/contacts\/?$/,
run: getContacts
},
{
method: 'POST',
url: /^\/contacts\/?$/,
run: createContact
},
{
method: 'GET',
url: /\/hi\//,
run: loadStatic
},
{
method: 'GET',
url: /^.*$/,
run: notFound
}
];
let server = http.createServer((req, res) => {
let route = routes.find(route =>
route.url.test(req.url) &&
req.method === route.method
);
route.run(req, res);
});
server.listen(3000);
Request URL: http://localhost:3000/hi/index.js
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Type: text/html
Date: Mon, 20 Aug 2018 23:41:45 GMT
Transfer-Encoding: chunked
以上是谷歌浏览器处理的响应。我首先不知道 (index) 是什么 - 它包含我所有的 html 脚本,以及 index.js 也一起发送(可能与 html doc 一起),这是应该的 javascript 文件的名称控制DOM。两者都包含html脚本,这是不对的,.js应该不同,它会首先尝试读取.js。此外,控制台中的错误显示“意外的'
**EDIT - 我在服务器脚本中添加了更多相关代码。很多经过编辑的功能,但这些功能都很好。这不是一个请求。 index.html、index.js(此文件控制 DOM 并在 index.html 中获取脚本标签)和 newserver.js(此文件的名称)位于我桌面上的同一文件夹中。希望对您有所帮助。
【问题讨论】:
-
您能否包含您的 JS 文件的其余部分,或有关您在项目中的文件结构的相关详细信息?
-
你确定 loadStatic 被击中了吗?尝试从该函数内部将某些内容记录到控制台以进行检查。另外,请考虑使用 express 框架,这样您就可以简化路由设置。
标签: javascript html node.js