最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

res.sendFile绝对路径

运维笔记admin12浏览0评论

res.sendFile绝对路径

res.sendFile绝对路径

如果我做了

res.sendfile('public/index1.html'); 

然后,我得到了一个服务器控制台警告

表示不赞成使用res.sendfile:使用res.sendFile代替

但它工作在客户端的罚款。

但是,当我将其更改为

res.sendFile('public/index1.html');

我得到一个错误

类型错误:路径必须是绝对的或指定根res.sendFile

index1.html不会被渲染。

我无法弄清楚的绝对路径是什么。我在同一水平public server.js目录。我从res.sendFileserver.js。我也宣布app.use(express.static(path.join(__dirname, 'public')));

加入我的目录结构:

/Users/sj/test/
....app/
........models/
....public/
........index1.html

什么是在这里指定的绝对路径?

我用快递4.x版

回答如下:

express.static中间件是res.sendFile分开的,所以用你的public目录的绝对路径初始化它不会做任何res.sendFile。您需要直接与res.sendFile使用绝对路径。有两种简单的方法做到这一点:

  1. res.sendFile(path.join(__dirname, '../public', 'index1.html'));
  2. res.sendFile('index1.html', { root: path.join(__dirname, '../public') });

注:__dirname返回当前执行的脚本在目录中根据你的情况,它看起来像server.jsapp/。所以,要到public,你需要背出第一个层次:../public/index1.html

注:path is a built-in module需要被required上面的代码工作:var path = require('path');

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论