首页 > 解决方案 > nodejs express:将 express.static 路径设置为父文件夹 (/..) 错误

问题描述

import express from "express"
import path from "path"

const app = express();
const __dirname = path.resolve();

app.use(express.static(`${__dirname}/../'webapp_test`))   //ERROR

app.get(`/`,(req,res)=>{
    res.sendFile(`${__dirname}/../webapp_test/todo.html`);
});

app.listen(8080);

通过将 express.static() 路径设置为带有转义序列的字符串文字${}

连接到localhost:8080like时发生错误

ForbiddenError: Forbidden
    at SendStream.error (WORKING DIRECTORY\node_modules\send\index.js:270:31)
    at SendStream.pipe (WORKING DIRECTORY\node_modules\send\index.js:553:12)
    at sendfile (WORKING DIRECTORY\node_modules\express\lib\response.js:1103:8)
    at ServerResponse.sendFile (WORKING DIRECTORY\node_modules\express\lib\response.js:433:3)
    at file://WORKING DIRECTORY/main.js:13:9
    at Layer.handle [as handle_request] (WORKING DIRECTORY\node_modules\express\lib\router\layer.js:95:5)
    at next (WORKING DIRECTORY\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (WORKING DIRECTORY\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (WORKING DIRECTORYt\node_modules\express\lib\router\layer.js:95:5)
    at WORKING DIRECTORY\node_modules\express\lib\router\index.js:281:22

path.join但是如果我用方法设置路径为

app.use(express.static(path.join(__dirname,`..`,`webapp_test`));

app.get(`/`,(req,res)=>{
    res.sendFile(path.join(__dirname,`..`,`webapp_test`,`todo.html`));
});

页面加载良好

我错过了什么?

标签: node.jsexpresspath

解决方案


这是因为“../”。这被认为是恶意的,将被 express 阻止,以防止网络用户在理论上通过在 url 中键入 .. 来访问计算机文件系统。您需要首先通过调用 path.resolve 来解析路径,然后整个计算机文件将其传递给 express。这本质上是 path.join 也这样做,因此在调用 path.join 之后它也可以工作。

这意味着你需要更换

res.sendFile(`${__dirname}/../webapp_test/todo.html`);

res.sendFile(path.resolve(`${__dirname}/../webapp_test/todo.html`));

app.use(express.static(`${__dirname}/../'webapp_test`))   //ERROR

app.use(express.static(path.resolve(`${__dirname}/../webapp_test`)))   //ERROR

另一种解决方案是为您的调用指定根目录,例如 ths :

res.sendfile(path, {'root': '/path/to/root/directory'});

希望回答你的问题。


推荐阅读