CNode

express中res.redirect 跳转的问题

问答
Ttianzeliang发布于11 年前最后回复8 年前10 回复47549 浏览0 收藏

我写的两个文件一个是index.js,另一个是hello.html,,我想要测试一下express,通过res.redirect来跳转到hello.html。 index.js内容如下:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
   //res.redirect('hello');
   res.redirect('./hello');
});
app.get('hello',function(req,res){
	res.end('asdf');
});
app.listen(3000);
console.log("http://localhost:3000");

可是运行后总是报错说,,cannot get ./hello 是我哪个语法写错了么。还是什么写错了呢

查看回复

回复 (10)

Y
yukjin#1·11 年前

/hello

T
tianzeliang#2·11 年前
引用 yukjin/hello

@yukjin /hello 不是表示从根目录读取么,,./hello /hello hello 各种路径都试过了,报的错误都是cannot get 加 路径,我也尝试过把hello.html文件放在各种路径下,结果都不行

是不是环境什么的错了啊,我也用sudo apt-get install express 安装了express,, 或者我的用法错了?

J
jokingZhang#3·11 年前

hello.html应该在views文件夹下存放。

D
DevinXian#4·11 年前

app.get('/hello', next...);

I
i5ting#5·11 年前

用res.sendfile

A
alsotang#6·11 年前

redirect 会给浏览器返回一个 302 状态码,对应的,返回的内容应该是路径。

1L 是对的

T
tianzeliang#7·11 年前
引用 jokingZhanghello.html应该在views文件夹下存放。

@jokingZhang 哦哦,,我没有用express命令搭建什么框架,,我就只写了index.js和hello.html两个文件,把它们放在同一个文件夹下。是我文件的位置没有放对么,还是我不可以直接这么用呢?

J
jokingZhang#8·11 年前

不好意思,前两天回家过年玩的太开心了...我刚才试了,下面的代码可以通过,而且不需要Hello.html就可以,只是传给浏览器请求。

var express = require('express');
var app = express();
app.get('/', function (req, res) {
//res.redirect('hello');
res.redirect('/hello');
});
app.get('/hello',function(req,res){
res.end('asdf');
});
app.listen(3000);
console.log("http://localhost:3000");
D
DMY-sunny#9·9 年前

把点去掉

J
jiazurongyu2015#10·9 年前

app.get('/hello',function(req,res){ <--少了1个/

app.get('/', function (req, res) { //res.redirect('hello'); res.redirect('/hello'); <--去掉点 });

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