节点JS:登录不工作

时间:2015-12-13 12:39:32

标签: javascript node.js mongodb express

我在Node上使用了Express .hbs模板。我使用护照来验证特定用户。我在MongoDB中使用的数据库。

这是我的注册路线:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var userServices = require('../services/user-services');

router.get('/', function(req, res, next) {

    var vm = {
    title: 'Join this web',
    };
  res.render('signup', vm);
});

router.post('/', function(req, res, next) {
  userServices.addUser(req.body, function(err){
    if(err){
    var vm = {
      title: 'Create an account',
      input: req.body,
      error: err
    };
    delete vm.input.password;
    return res.render('signup', vm);
  }
      req.login(req.body, function(err) {
      res.redirect('/profile');
    });
   });
});
router.post('/login', passport.authenticate('local'), function(req, res, next){
  res.redirect('/profile');
});

module.exports = router;

这是我的登录路线:

var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
  if (req.user) {
    return res.redirect('/profile');
  }
  res.render('login', { title: 'Login' });
});

module.exports = router;

我已在passport-congig文件中定义了护照的配置:

module.exports=function(){
    var passport = require('passport');
    var passportLocal = require('passport-local');
    var userServices = require('../services/user-services');

    passport.use(new passportLocal.Strategy({usernameField: 'email'}, function(email, password, next) {
        userServices.findUser(email, function(err, user){
            if(err){
                return next(err);
            }
            if(!user||user.password!==password){
                return next(null, null);
            }
            next(null, user);
        });
    }));

    passport.serializeUser(function(user, next){
        next(null, user.email);
    });

    passport.deserializeUser(function(user, next){
        userServices.findUser(email, function(err, user){
            next(err, user);
        });
    });
};

此外,这是我的app.js与护照相关的代码:

var passportConfig = require('./auth/passport-config');
passportConfig();

var app = express();

app.use(expressSession({
    secret:'trawel man',
    saveUninitialized: false,
    resave: false
}));

app.use(passport.initialize());
app.use(passport.session());

以下是我收到的错误的堆栈跟踪:

Error: Not Found

at C:\Users\James\MEAN\app.js:56:15
at Layer.handle [as handle_request] (C:\Users\James\MEAN\node_modules\express\lib\router\layer.js:82:5)
at trim_prefix (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:302:13)
at C:\Users\James\MEAN\node_modules\express\lib\router\index.js:270:7
at Function.proto.process_params (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:321:12)
at next (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:261:10)
at C:\Users\James\MEAN\node_modules\express\lib\router\index.js:603:15
at next (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:246:14)
at Function.proto.handle (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:166:3)
at router (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:35:12)
at Layer.handle [as handle_request] (C:\Users\James\MEAN\node_modules\express\lib\router\layer.js:82:5)
at trim_prefix (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:302:13)
at C:\Users\James\MEAN\node_modules\express\lib\router\index.js:270:7
at Function.proto.process_params (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:321:12)
at next (C:\Users\James\MEAN\node_modules\express\lib\router\index.js:261:10)
at C:\Users\James\MEAN\node_modules\express\lib\router\index.js:603:15

这是我在服务器控制台上得到的:

POST /login 404 32.453 ms - 2847

我不知道为什么这不起作用。我是Node的新手。有人帮助我。

2 个答案:

答案 0 :(得分:1)

您错过了@model MVC_myfirst_Mvcapplication.Models.Person @{ ViewBag.Title = "Create"; } <h2>Create</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Person</legend> <div class="editor-label"> @Html.LabelFor(model => model.First) </div> <div class="editor-field"> @Html.EditorFor(model => model.First) @Html.ValidationMessageFor(model => model.First) </div> <div class="editor-label"> @Html.LabelFor(model => model.Last) </div> <div class="editor-field"> @Html.EditorFor(model => model.Last) @Html.ValidationMessageFor(model => model.Last) </div> <div class="editor-label"> @Html.LabelFor(model => model.Birthdate) </div> <div class="editor-field"> @Html.EditorFor(model => model.Birthdate) @Html.ValidationMessageFor(model => model.Birthdate) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> 的路线,这就是为什么您的最终“未找到”路线被调用的原因。

使用

添加路线
/profile

并且不会抛出该错误

编辑:

好像你在尝试登录时遇到错误,而不是之后。那是因为您router.get('/profile', function (req, res, next) { var vm = { name : req.user ? req.user.name:null }; res.render('profile', vm); }) 的路线位于错误的文件中。在您的登录路由文件中,添加以下内容:

POST login

(确保导入依赖项)

从注册路线中删除router.post('/', passport.authenticate('local'), function(req, res, next){ res.redirect('/profile'); });

答案 1 :(得分:-1)

import User from "../models/User";
import Role from "../models/Role";

import jwt from "jsonwebtoken";
import config from "../config";

//const timer1 = (ms) => new Promise((res) => setTimeout(res, ms));
export const signUp = async (req, res) => {

    try {
        // Getting the Request Body
       
        const {
            username,
            email,
            password,
            roles,
            nombres,
            apellidos,
            status,
            telefono,
            cedula,
            foto,
            typo,
        } = req.body;
        // Creating a new User Object
        const newUser = new User({
            username,
            email,
            nombres,
            apellidos,
            status,
            telefono,
            foto,
            cedula,
            typo,
            password: await User.encryptPassword(password),
        });

        // checking for roles
        if (req.body.role) {
            newUser.roles = req.body.role;
        } else {
            const role = await Role.findOne({
                name: "Docente"
            });
            newUser.roles = [role._id];
        }
         
        // Saving the User Object in Mongodb
        newUser.roles = req.body.role;
        const savedUser = await newUser.save();

        return res.status(200).json({
            savedUser
        });
    } catch (error) {
        console.log(error);
        return res.status(500).json(error);
    }
};
//---------------------------------------------------------LOGIN ACCESS--------------------------
export const signin = async (req, res) => {
    try {
        // EL CUERPO DE CORREO O EL CUERPO DE USERNAME
        const userFound = await User.findOne({
            email: req.body.email
        }).populate(
            "roles"
        );
        //VERIFICAR sI EL USUARIO EXISTE EN BASE DE DATOS
        if (!userFound) return res.status(400).json({
            message: "User Not Found 1"
        });
        //SI EXISTE PASA A VERIFICAR Y DESENCRIPTAR LA CONTRASEÑA
        const matchPassword = await User.comparePassword(
            req.body.password,
            userFound.password
        );
        //RETORNA EL RESULATDO
        if (!matchPassword)
            return res.status(401).json({
                token: null,
                message: "Invalid Password",
            });
        //OPTENERMOS EL ROL
        var toles = null
        const roles = await Role.find({
            _id: {
                $in: userFound.roles
            }
        });
        for (let i = 0; i < roles.length; i++) {
            toles = roles[i].name
            console.log(roles[i].name)
            
        }

        const token = jwt.sign({
            id: userFound._id,
            name: userFound.apellidos+" "+ userFound.nombres,//username
            email: userFound.email,
            foto: userFound.foto,
            role: toles
        }, config.SECRET, {
            expiresIn: 86400, // 24 hours
        });

        res.json({
            token
        });
    } catch (error) {
        console.log(error);
    }
};

//ctl

import { Router } from "express";
const router = Router();

import * as authCtrl from "../controllers/auth.controller";
import { verifySignup } from "../middlewares";

router.use((req, res, next) => {
  res.header(
    "Access-Control-Allow-Headers",
    "x-access-token, Origin, Content-Type, Accept"
  );
  next();
});

router.post(
  "/signup",
  [verifySignup.checkDuplicateUsernameOrEmail, verifySignup.checkRolesExisted],
  authCtrl.signUp
);

router.post("/signin", authCtrl.signin);

export default router;