nodejs/expressjs重定向不起作用 [英] nodejs/expressjs redirect does not work

查看:109
本文介绍了nodejs/expressjs重定向不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在expressjs中提供带有重定向功能的网页.但是它某种程度上是行不通的.我一定在这里呆呆.

I tried to serve a webpage with redirect function in expressjs. But it somehow cannot work. I must be dumb on something here.

index.html:

index.html:

<html>

<body>
    <div id="clicked"> not clicked </div>
</body>

</html>

server.js:

server.js:

var express = require("express");
var app     = express();

app.get('/', function(req, res) {
    console.log("reached root!");
    res.redirect("index.html");
});
app.listen(9876);

两个文件都在同一目录中.我可以在浏览器控制台上看到日志已到达日志",但出现404错误:无法获取/index.html".但是,如果我重定向到外部网页,则可以正常工作.如果我更改"res.redirect("index.html");到"res.redirect(" http://google.com ");,它可以完美运行.

Both files are in the same directory. I can see the log "reached log" on browser console but I got a 404 error: "Cannot GET /index.html". However, if I redirect to a outside webpage, it can work. If I change "res.redirect("index.html");" to "res.redirect("http://google.com");", it can work perfectly.

推荐答案

node.js默认情况下不提供任何文件.因此,硬盘上的哪些文件都没有关系.如果没有办法提供这些文件,Express将永远不会发送它们.

node.js does not serve any files by default. So, it doens't matter what files on on your hard disk. If there's no route to serve those files, Express will never send them.

因此,如果您要重定向到/index.html ,则需要一条路由来满足该请求.就像您的服务器一样,该请求将生成404(找不到路由/文件).

So, if you're going to redirect to /index.html, then you need a route to serve that request. As your server is now, that request is going to generate a 404 (route/file not found).

var express = require("express");
var app     = express();

app.get('/', function(req, res) {
    console.log("reached root!");
    res.redirect("/index.html");
});
app.get('/index.html', function(req, res) {
    console.log("reached root!");
    res.sendFile("index.html");
});
app.listen(9876);

也许您想要做的只是渲染"index.html"而不进行重定向.这可能适用于您的一条路线.

Perhaps what you want to do is to just render 'index.html' without a redirect. That could work with the one route you have.

var express = require("express");
var app     = express();

app.get('/', function(req, res) {
    console.log("reached root!");
    res.sendFile("index.html");
});
app.listen(9876);

这些示例假定文件index.html位于应用程序目录中.如果它位于其他位置,则需要适当地调整 sendFile()的路径.

These examples assume the file index.html is in the app directory. If it is located elsewhere, then you need to adjust the path for sendFile() appropriately.

对于静态文件,您还可以使用 express.static()自动提供整个文件目录.请参见 express.static()文档有关详细信息.

For static files, you can also use express.static() to automatically serve a whole directory of files. See the express.static() doc for details.

这篇关于nodejs/expressjs重定向不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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