【问题标题】:Node.js path errorNode.js 路径错误
【发布时间】:2015-04-20 22:46:26
【问题描述】:

在我的 server.js 下我有以下

app.use(express.static(__dirname + '/public'));

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

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

当我启动服务器并在http://localhost:8000 上呈现时,我能够看到 index.html,但在 http://localhost:8000/report 上我无法呈现 report.html,而是出现路径错误 path must be absolute或指定 root 到 res.sendFile

我的目录结构是

public
   index.html
   report.html

为什么会出现这个错误?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    默认情况下,express.static() 将在仅请求/ 时提供index.html(请参阅reference in the doc)。因此,您的 index.htmlexpress.static() 中间件提供服务,而不是由您的 app.get('/', ...) 路由提供服务。

    因此,您的两条 app.get() 路线可能会遇到完全相同的问题。第一个没有被调用,因为您的 express.static() 配置已经在处理该请求并发回 index.html

    /report 路由没有被express.static() 处理,因为reportreport.html 不是同一个请求。因此,中间件不会处理请求,因此您配置错误的 app.get('/report', ...) 处理程序会被调用,并且您会收到错误配置的错误消息。

    这应该就是你所需要的:

    var express = require("express");
    var app = express();
    
    app.use(express.static(__dirname + '/public'));
    
    app.get('/report', function(req, res){
        res.sendFile(__dirname + "/public/report.html");
    });
    
    app.listen(8080);
    

    或者,您可以使用路径模块并将片段与path.join() 连接起来:

    var path = require("path");
    

    然后,用这个来提供文件:

    res.sendFile(path.join(__dirname, 'public', 'report.html'));
    

    在我自己的示例 nodejs 应用程序中,这些 res.sendFile() 选项中的任何一个都可以使用。

    【讨论】:

    • 我确实尝试过这个 res.sendFile(__dirname + '/public/report.html') 但它输出了一个 Cannot GET /report
    • 我现在正在使用手机,但我想知道将路由更改为/report/ 是否有帮助?
    • 这样做了 res.sendFile('report.html',{root: __dirname + '/public/'});
    • @user3750842 - 当我自己尝试时,这些都可以:`res.sendFile(path.join(__dirname, 'public', 'report.html'));res.sendFile(__dirname + "/public/report.html");
    【解决方案2】:

    npm 安装路径

    那么,你必须指定根路径:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    app.use(express.static(__dirname + '/public'));
    
    app.get('/', function(req, res){
     res.sendFile('index.html');
    });
    
    app.get('/report', function(req, res){
        res.sendFile('report.html', { root: path.join(__dirname, './public') });
    });
    
    app.listen(8000);
    

    【讨论】:

    • 这很奇怪。我只是在单独的 linux 和 windows 上尝试过,并且在两者上都很好用。你有安装路径模块吗?我在根文件夹中有一个 server.js,在公共文件夹中有 index.html、report.html。公用文件夹在 server.js 旁边。
    • 是的,我安装了路径模块,但是当我这样做时 res.sendFile('report.html',{root: __dirname + '/public/'});它奏效了
    猜你喜欢
    • 2013-08-02
    • 1970-01-01
    • 2017-04-15
    • 2020-11-18
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多