跳到主要内容
CNode

res.render和res.sendFile有什么区别?

问答
HhelloMane发布于 11 年前最后回复 11 年前
15288850

我之前看别人的代码用res.sendFile实现一个get方法的页面显示,他用的express 3.x 现在我用res.sendFile,(我的是express 4.x)但是却出现错误( Failed to lookup view "error" in views directory……) 后面改用res.render就行了,请问一下有什么区别?

============================app.js中写的是这样的: //其余代码省略 var ejs =require('ejs'); var routes = require('./routes/index'); //其余代码省略 app.set('views', __dirname + '\\views'); app.engine('.html', ejs.__express); app.set('view engine', 'html'); //其余代码省略 app.get('/', routes.hello);

=============================routes/index.js var express = require('express'); exports.hello = function(req, res){ res.render('index.html', {title:'index'}); }

===========================views/index.html

<% include head.html %> <%= title %> hello world111111
查看回复

回复 (15)

I
iyuq#1411 年前

我明白了,你的路由文件是放在routes文件夹下的,那样的话,sendFile路径应该使用 path.resolve(__dirname,'../views/index.html')用这个试试吧

H
helloMane#1311 年前
引用 giscafer看源码。

@giscafer 主要源码我已经在原文加上去了,你看看哪里有问题

H
helloMane#1211 年前
引用 gjc9620能上demo吗 估计是楼主代码写错 或者 文件夹没放对

@gjc9620 主要部分的代码我已经在原文写好了,麻烦你看看,我看不出有什么问题

G
gjc9620#1111 年前

能上demo吗 估计是楼主代码写错 或者 文件夹没放对

H
helloMane#1011 年前
引用 kleshhttp://expressjs.com/en/4x/api.html res.sendFile Transfers the file at the given path. Sets the ...

@klesh 这么说来的话,如果是要实现页面显示首选render咯?我试了一下sendFile发送一个zip文件依然错误,状态是500.但是用download就可以实现。。。真的是越来越看不懂sendFile了。。。

H
helloMane#911 年前
引用 iyuqrend方法是不需要.html文件后缀的,而sendFile需要写文件后缀,检查下是不是这个问题。

@iyuq 不是。。。我sendFile写了.html后缀,甚至加了views/路径都没办法,状态是500

K
klesh#811 年前

http://expressjs.com/en/4x/api.html#res.sendFile Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file. 这个是直接发送文件的意思,比如说给客户端发一个 rar 文件,图片,html什么的都可以,

http://expressjs.com/en/4x/api.html#res.render Renders a view and sends the rendered HTML string to the client. Optional parameters: 这个是渲染模板并输出的意思,也就是针对views下面的模板文件进行组合生成html然后发送给客户端

I
iyuq#711 年前

rend方法是不需要.html文件后缀的,而sendFile需要写文件后缀,检查下是不是这个问题。

H
helloMane#611 年前
引用 gjc9620如果是jade或者是ejs啥的模板的话要用render 对于html好像是没什么区别的 =。=

@gjc9620 我又试了一下,弄到public中也没办法显示了,蛋疼。。。一下又没有线索了

H
helloMane#511 年前
引用 giscafer看源码。

@giscafer 我又试了一下,现在弄到public中也没办法显示了,只能用render不能用sendFile。。。这是什么鬼

H
helloMane#411 年前
引用 giscafer看源码。

@giscafer app.set('views', __dirname + '\views'); app.engine('.html', ejs.__express); app.set('view engine', 'html');

也就这样写的,在views文件夹里的html文件确实没办法sendFile,但是弄到public中就可以sendFile。。。 真的感觉挺怪的

H
helloMane#311 年前
引用 gjc9620如果是jade或者是ejs啥的模板的话要用render 对于html好像是没什么区别的 =。=

@gjc9620 app.engine('.html', ejs.__express); app.set('view engine', 'html'); 也就只是这样写的,应该不算是ejs模板吧。。。 而且我发现如果把文件放在public下面就可以sendFile,然而在views下面就无法sendFile。 真的搞不懂。。。

G
gjc9620#211 年前

如果是jade或者是ejs啥的模板的话要用render 对于html好像是没什么区别的 =。=

G
giscafer#111 年前

看源码。

参与回复

登录后即可参与回复。登录