express中res.redirect 跳转的问题
发布于 9 年前 作者 tianzeliang 46476 次浏览 最后一次编辑是 8 年前 来自 问答

我写的两个文件一个是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 回复

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

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

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

app.get(’/hello’, next…);

用res.sendfile

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

1L 是对的

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

不好意思,前两天回家过年玩的太开心了…我刚才试了,下面的代码可以通过,而且不需要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");

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

app.get(’/’, function (req, res) { //res.redirect(‘hello’); res.redirect(’/hello’); <–去掉点 });

回到顶部