首页 > 解决方案 > 具有本地护照身份验证的 nextjs 服务器响应错误

问题描述

Pages/api/signup.js 注册 api

import dbConnect from '../../utils/dbConnect'
import Author from '../../models/Author'
import auth from "../../middleware/auth"
import isEmail from 'validator/lib/isEmail';
import normalizeEmail from 'validator/lib/normalizeEmail';
import bcrypt from 'bcryptjs';
import nextConnect from "next-connect"

const handler = nextConnect()

handler.use(auth)

handler.post(async (req, res) => {

  await dbConnect()

try {                                                                                                                                           
    const {name, image, password} = req.body;                                 
    const email = normalizeEmail(req.body.email);

     if (!isEmail(email)) {                                                   res.status(400).send('The email you entered is invalid.');
        return;
     }

     if (!password || !name || !image) {
        res.status(400).send('Missing field(s)');
        return;                                                            }

     // check if email existed

    Author.exists({email: email}, async (error, result)=>{
        if(result) {
          res.status(403).send('The email has already been used.');
          return;
        }else {
          const hashedPassword = await bcrypt.hash(password, 10);
          const author = await Author.create({
                  email,
                  password: hashedPassword,
                  name,                                                                 image
          }) /* create a new model in the database */

         console.log("new author registered successfully")

         req.logIn(author, (err) => {                                             if (err) throw err;
         // when we finally log in, return the (filtered) user object
            res.status(201).json({
             author: {name, email, image}})
            });
         }
        })
    } catch (error) {
    console.log(error)
    }
})

export default handler;

登录API 页面/api/login.js

import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import passport from '../../lib/passport'

const handler = nextConnect()

handler.use(auth)

handler.post(passport.authenticate('local'), (req, res) => {
  // return our user object
  const { email, _id, name, image} = req.author
  const author = { email, name, image }                                 res.json( {author} )                                                });                                                                   
export default handler

中间件函数 middleware/auth.js

import nextConnect from 'next-connect'
import passport from '../lib/passport'
import session from '../lib/session'
import dbConnect from "../utils/dbConnect"

const auth = nextConnect()

auth
  .use(dbConnect)
  .use(session)
  .use(passport.initialize())
  .use(passport.session())                                            
export default auth

护照本地策略代码 lib/passport.js

import passport from 'passport'
import LocalStrategy from 'passport-local'
import Author from "../models/Author"

passport.serializeUser(function(author, done) {
  done(null, author.email);                                           });                                                                   
passport.deserializeUser(function(email, done) {
  User.findOne({email: email}, function(err, author) {                    done(err, author);
  });
});

passport.use(new LocalStrategy(
  function(email, password, done) {
    Author.findOne({ email: email }, async  function (err, author) {        if (err) { return done(err); }
      if (!author) { return done(null, false); }
      if (!(await bcrypt.compare(password, author.password) )){
         return done(null, false);
      }
      return done(null, author);
    });
  }
)
)


export default passport

获取部分 lib/session.js的代码

const session = require('express-session');
const MongoStore = require('connect-mongo').default;
                                                                      
export default function (req, res, next) {
  const mongo = process.env.MONGODB_URL
  return session({
    secret: process.env.TOKEN_SECRET,
    store: MongoStore.create({ mongoUrl: `${mong}`})
  })(req, res, next)
}

我的数据库连接

实用程序/dbConnect

import mongoose from 'mongoose';

const dbConnect = async (req, res, next) => {

  try {                                                                                                                                         if (!global.mongoose) {                                                global.mongoose = await mongoose.connect(process.env.MONGODB_URL,{
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
      });

    }

  } catch (err) {
    console.error(err);
  }

  // You could extend the NextRequest interface
  // with the mongoose instance as well if you wish.                    //req.mongoose = global.mongoose;

  return next();                                                      
};

export default dbConnect

这些是 API 的代码,我不确定是否应该从发出请求的客户端添加代码?

我真的无法弄清楚这段代码有什么问题,每当我发出发布请求时,我都会收到 500 响应错误代码。

抱歉,代码太长了

标签: next.jspassport-localpassport-local-mongoose

解决方案


推荐阅读