使用html获取未在express中调用的路由

时间:2017-05-01 16:02:15

标签: javascript node.js express

我有一个非常简单的应用程序,所以我认为我不需要像棱角分明的完整的前端模板,我真的不想使用Jade

app.get('*', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

基本上我正在返回一个html文件,我可以调用其他html文件,如

login.html
signup.html

但令我困惑的是我的路线没有被调用。例如,我向/ login发送GET请求,但没有“LOGIN GET”输出

//编辑:即使使用req,res,我也可以删除下面的这个功能并仍然接收index.html

app.get('/login',function(req,res){ 
  console.log("LOGIN GET")
  res.sendFile( path.join( __dirname, 'public', 'login.html' ));    
});

如果未调用我的路线,login.html如何发送到客户端?

3 个答案:

答案 0 :(得分:0)

缺少路由处理程序的req和res参数。对于静态文件,您还可以关注https://expressjs.com/en/starter/static-files.html

app.get('/login',function(req, res){ 
  console.log("LOGIN GET")
  res.sendFile( path.join( __dirname, 'public', 'login.html' ));    
});

答案 1 :(得分:0)

您应该使用Express路由器。

var router = express.Router();

然后,你可以得到

router.get("/login",function(req,res){
  console.log("LOGIN GET")
  res.sendFile( path.join( __dirname, 'public', 'login.html' )); 
});

答案 2 :(得分:0)

我的猜测是你首先要宣布这个全能路线:

app.get('*', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

app.get('/login',function(req,res){ 
  console.log("LOGIN GET")
  res.sendFile( path.join( __dirname, 'public', 'login.html' ));    
});

由于/login*匹配,因此Express也会使用第一条路径来处理/login的请求。通常,使用Express,您需要首先声明更具体的路线:

app.get('/login',function(req,res){ 
  console.log("LOGIN GET")
  res.sendFile( path.join( __dirname, 'public', 'login.html' ));    
});

app.get('*', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

其他HTML文件的工作原因是您可能也在使用express.static()(但未显示)。