【问题标题】:Node.js server responding with javascript file, not main .html?Node.js 服务器使用 javascript 文件而不是主 .html 响应?
【发布时间】: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


【解决方案1】:

index.js 不像您想象的那样与index.html“一起发送”。浏览器首先请求/hi。当您发送该 HTML 文件的内容时,浏览器会解析该 HTML 文件以及它在 HTML 中找到的任何 <script src="xxx"> 标记,浏览器然后向您的服务器发出单独的请求,以获取脚本中的任何 src 文件标签,例如index.js

因为您没有/index.js 的路由,它将匹配您的notfound 路由(您没有显示代码)。仅供参考,您的未找到路由可能应该返回 404 状态,因为这使调试更容易(浏览器控制台中会出现 404 错误,很容易看到)。

您需要为您的 HTML 文件引用的所有资源(脚本、css 文件、图像等)提供路由。默认情况下,node.js 不提供任何文件(与其他一些 Web 服务器不同)。它只为您专门为其编写路由和编写要发送的代码的文件提供服务。

可以编写一个通用路由,为特定目录中与请求完全匹配的任何文件提供服务。 Express 框架具有这样的功能,称为express.static()。它对于提供只需要发送静态文件的静态资源非常有用。如果您打算继续编写自己的 http 框架而不使用已经构建的框架,那么您可能想要编写这样一个静态匹配器。然而,重要的是,您将静态文件匹配器指向仅包含公共文件的目录,这样人们就不会无意中访问私有服务器文件。而且,还必须防止诸如.. 或根路径之类的东西出现在 URL 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2017-12-27
    • 2017-07-18
    相关资源
    最近更新 更多