Node.jsredirect到另一个node.js文件

我想要从一个nodejs文件重新指向另一个nodejs文件。 我用res.redirect(URL),但是当执行它说“不能GET / nodepage”

目前我正在使用

// Handler for GET / app.get('/nodepostgres', function(req, res){ res.redirect('/nodepost.js?a=1'); }); 

我认为有几件事情你没有正确解释,或者在你的问题中没有正确理解。

我不确定你的意思是“从一个nodejs文件redirect到另一个nodejs文件”。 您似乎认为节点脚本文件对应于一个URL(或一个页面)。 那是错的 节点脚本对应于可能(或不可以)通过多个URL公开多个页面的应用程序,并且可以从其他脚本文件(您将为站点或应用程序运行单个根脚本文件)导入应用程序逻辑。 这与你所知道的(vannilla,没有框架)PHP是完全不同的。

通过不同的URL公开不同的页面称为路由,所有关于路由的Express文档可以在这里find 。

我的理解是,你试图做一个function/页/ Url脚本:nodepost.js文件是一个页面。 代码组织是一件好事,但我们首先关注node + express是如何工作的。

据我所知,你应用程序有几个暴露的url,让我们说:

  • “/“ 主页
  • “/ nodepostgre”(也许接受'a'arg?
  • “/ nodepost”接受一个arg:a

注意:我们忘记了file = page的id,我们不希望在URL上出现扩展名,所以nodepost.js变成了nodepost

你可以做的是设置3个url展览:

 app.get('/', function(req, res) { res.render('home'); }); // render the home page app.get('/nodepost', function(req, res) { // expose the nodepost function var a = req.params.a; doSomethingWith(a); // res.render, res.send ? whatever you want... ]); app.get('/nodepostgres', function(req, res){ // use of res.redirect(url[, status]) res.redirect('/nodepost'); }); 

那是你要的吗 ?

那么,这是一个更好的处理参数(“a”)的方法。

 app.get('/notepost/:a', function(req, res) { // called via /nodepost/here_goes_a_valu ; no "?" var a = req.params.a; 

});

为什么更好?

  1. 尊重REST (可能不是形容rest的最佳链接,但…)
  2. 允许你公开没有参数的“/ nodepost”
  3. 当然还有一百万其他的东西