res.sendFile 绝对路径 [英] res.sendFile absolute path

查看:47
本文介绍了res.sendFile 绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我做一个

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

然后我收到服务器控制台警告

then I get a server console warning

express deprecated res.sendfile:使用 res.sendFile 代替

express deprecated res.sendfile: Use res.sendFile instead

但它在客户端运行良好.

but it works fine on the client side.

但是当我把它改成

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

我收到一个错误

TypeError: path must be absolute 或指定 root to res.sendFile

TypeError: path must be absolute or specify root to res.sendFile

index1.html 不呈现.

我无法弄清楚绝对路径是什么.我有与 server.js 处于同一级别的 public 目录.我正在使用 server.js 执行 res.sendFile.我还声明了 app.use(express.static(path.join(__dirname, 'public')));

I am unable to figure out what the absolute path is. I have public directory at the same level as server.js. I am doing the res.sendFile from with server.js. I have also declared app.use(express.static(path.join(__dirname, 'public')));

添加我的目录结构:

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

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

What is the absolute path to be specified here ?

我使用的是 Express 4.x.

I'm using Express 4.x.

推荐答案

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

The express.static middleware is separate from res.sendFile, so initializing it with an absolute path to your public directory won't do anything to res.sendFile. You need to use an absolute path directly with res.sendFile. There are two simple ways to do it:

  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.

Note: __dirname returns the directory that the currently executing script is in. In your case, it looks like server.js is in app/. So, to get to public, you'll need back out one level first: ../public/index1.html.

注意:path 是一个内置模块 需要 required 才能使上述代码工作:var path = require('path');

Note: path is a built-in module that needs to be required for the above code to work: var path = require('path');

这篇关于res.sendFile 绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆