无法发出HTTP帖子请求

时间:2018-04-28 09:04:01

标签: node.js express

我正在尝试使用HTTP post请求登录。

app.js

//login
app.get('/login', indexRouter); // call to login site
app.post('/login',indexRouter); // post to /users/login site

users.js

router.get('/', function(req, res, next) {
    var message = '';
   var sess = req.session; 

   if(req.method == "POST"){
      var post  = req.body;
      var name= post.user_name;
      var pass= post.password;

      var sql="SELECT id, first_name, last_name, user_name FROM `users` WHERE `user_name`='"+name+"' and password = '"+pass+"'";                           
      db.query(sql, function(err, results){      
         if(results.length){
            req.session.userId = results[0].id;
            req.session.user = results[0];
            console.log(results[0].id);
            res.redirect('/users/home/dashboard');
         }
         else{
            message = 'Wrong Credentials.';
            res.render('index.ejs',{message: message});
         }

      });
   } else {
      res.render('index.ejs',{message: message});
   }         
}); 

当我点击登录时,它会将我引导至http://localhost:3000/login并找不到Eror 404。我从我的主页http://localhost:3000登录。

我是否错误地执行了POST请求?

1 个答案:

答案 0 :(得分:0)

您需要将路由器划分为两种方法:router.getrouter.post。 例如:

// app.js
// login
app.use('/login', indexRouter); 

// users.js
// call to login site
router.get('/', function(req, res, next) {
  var message = '';
  var sess = req.session; 
  res.render('index.ejs',{message: message});
});

// users.js
// post to /users/login site
router.post('/', function(req, res, next) {
  var message = '';
  var sess = req.session; 

  var post  = req.body;
  var name= post.user_name;
  var pass= post.password;

  var sql="SELECT id, first_name, last_name, user_name FROM `users` WHERE `user_name`='"+name+"' and password = '"+pass+"'";                           
  db.query(sql, function(err, results){      
     if(results.length){
        req.session.userId = results[0].id;
        req.session.user = results[0];
        console.log(results[0].id);
        res.redirect('/users/home/dashboard');
     }
     else{
        message = 'Wrong Credentials.';
        res.render('index.ejs',{message: message});
     }
  });
});