在Express中简单redirect与静态文件

我是Node和Express的新手。 我有一个静态html页面,用户通过ajax发送他的用户名到我的服务器。 然后我想redirect他到另一个HTML文件。

var express = require("express"); var bodyParser = require("body-parser"); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(express.static(__dirname + "/public/arena.html")); app.get('/',function(req,res){ res.sendFile(__dirname + "/public/index.html"); }); app.post('/login',function(req,res){ var username=req.body.username; console.log("User name = "+username); res.redirect(__dirname + "/public/arena.html"); }); var server = app.listen(3000); 

我得到的用户名,也在浏览器的响应,但服务器不会redirect到arena.html。 我也没有得到任何错误。

为什么这些“容易”的事情在Node中如此困难?

非常感谢你们的帮助。

在这种情况下的问题是,它看起来像你有一些testing(debugging?)代码插入到您的POST路由,正在停止redirect调用运行。

这里是你的程序的修改后的版本, 它将以你想要的方式redirect用户:

 var express = require("express"); var bodyParser = require("body-parser"); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(express.static(__dirname + "/public/arena.html")); app.get('/', function(req, res) { res.sendFile(__dirname + "/public/index.html"); }); app.get('/arena', function(req, res) { res.sendFile(__dirname + "/public/arena.html"); }); app.post('/login', function(req, res) { var username = req.body.username; console.log("User name = " + username); // Note how I'm redirecting the user to the /arena URL. // When you issue a redirect, you MUST redirect the user // to a webpage on your site. You can't redirect them to // a file you have on your disk. res.redirect("/arena"); }); app.listen(3000); 

我不得不做几件事情才能做到这一点:

  1. 摆脱你的呼吁res.end 。 每当你调用res.end ,它都会结束这个请求,所以在这个调用之后发生的任何代码都不会运行。

  2. 我必须创造一个新的路线/arena 。 这只是呈现您创build的arena.html文件。 如果您想将用户redirect到竞技场页面,则这是必需的。

  3. 我不得不更新你的redirect代码,以实际redirect用户到/arena (我在第2步创build的新路线),以便用户然后击中你的/arena路线,最后找回你想要显示的模板。

你的res.redirect函数永远不会被执行,因为你正在从那个语句之前的函数返回。

你传递一个URL到res.redirect() 。 这个URL应该是一个URL,你有一个适当的路由,它将提供所需的文件。

相反,你正在做:

 res.redirect(__dirname + "/public/arena.html"); 

但是,这根本不是一个URL。 这是您的本地硬盘上的path名称。 res.redirect()发回一个URL到浏览器,如果浏览器redirect,它将从头开始请求这个URL作为分支的新请求。 所以,你需要发送一个URL(而不是一个path),你需要发送一个URL,你有一个路由configuration为将服务于所需的文件。

它也看起来像你的express.static()语句可能是不正确的。 为了更好地帮助我们,我们需要知道硬盘上的静态HTML文件相对于__dirname ,我们需要知道您希望如何使用这些URL。 例如,您是否要求/arena.html提供__dirname + /public/arena.html ? 那是你在做什么? 请解释一下这个部分,以便我们可以更具体地build议您的express.static()语句。

如果是这样,那么你可以改变你的redirect到:

 res.redirect("/arena.html");