What method should I use for a login (authentication) request?

后端 未结 6 810
天涯浪人
天涯浪人 2020-12-23 10:41

I would like to know which http method I should use when doing a login request, and why? Since this request creates an object (a user session) on the server, I think it shou

6条回答
  •  醉酒成梦
    2020-12-23 11:41

    For Login I use POST, below is my code for LOGIN method I used Nodejs with Express and Mongoose

    your router.js
         const express = require("express");
         const router = express.Router();
    
         router.post("/login", login);
    
    your controller.js
         export.login = async(req, res) => {
             //find the user based on email
             const {email, password} = req.body; 
    
               try{
                    const user =  awaitUser.findOne({email});
                    if(user==null) 
                     return res.status(400).json({err : "User with 
                             email doesnot exists.Please signup"});
              }
               catch(error){
                     return res.status(500).json({err : 
                                         error.message});
                   }
    
             //IF EVERYTHING GOES FINE, ASSIGN YOUR TOKEN
              make sure you have JWT installed 
             const token = jwt.sign({_id: user._id}, YOUR_SECRET_KEY);
    
             res.cookie('t');
    
             const {_id, name, email} = user;
             return res.json({token, user : {_id, email, name}});
    
    
    
         }
    

提交回复
热议问题