具有护照本地身份验证的 nextjs 服务器响应错误

问题描述

页面/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/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,image} = req.author
  const author = { email,image }                                 res.json( {author} )                                                });                                                                   
export default handler

中间件功能 中间件/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,next)
}

我的数据库连接

utils/dbConnect

import mongoose from 'mongoose';

const dbConnect = async (req,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 响应错误代码

抱歉代码太长了

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)