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

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

问题描述

如果我执行

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

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


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


但它在客户端工作正常。



但是当我将其更改为



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

我收到错误


TypeError:path必须是绝对值,或指定root到 res.sendFile


index1.html 不呈现。



我无法弄清楚绝对路径是。与 server.js 相同级别的 public 目录。我正在使用 server.js 执行 res.sendFile 。我也声明了 app.use(express.static(path.join(__ dirname,'public')));



添加我的目录结构

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

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



我正在使用Express 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.js app / 中。因此,要获得 public ,您需要先退出一级: ../ public / index1.html



注意: 路径是一个内置模块,需要 require d代表上述代码工作: var path = require('path');


If I do a

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

then I get a server console warning

express deprecated res.sendfile: Use res.sendFile instead

but it works fine on the client side.

But when I change it to

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

I get an error

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

and index1.html is not rendered.

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')));

Adding my directory structure:

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

What is the absolute path to be specified here ?

I'm using Express 4.x.

解决方案

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') });

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.

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天全站免登陆