node.js - 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:8080
like时发生错误
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`));
});
页面加载良好
我错过了什么?
解决方案
这是因为“../”。这被认为是恶意的,将被 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'});
希望回答你的问题。
推荐阅读
- amazon-s3 - S3 使用预签名 URL 上传和提供图像
- python - Python-NumPy 对每一行进行不同的切片
- c - 打印小写、大写和数字个数
- javascript - 在香草javascript中获取事件目标的ID
- node.js - 如何根据正则表达式从 Google Cloud Storage 存储桶中获取文件?
- javascript - 为什么我在执行“for循环”以在ChartJS中显示“datasets.data”后只得到一个值
- .net - Application Insights - 从 .net 核心中间件添加属性
- scala - Scala 循环中的代码效率,向上计数还是向下计数?
- erlang - 二进制和 Unicode 字符串
- vim - 几个 vim/emmet 命令命令不起作用