尝试登录我的 Next.js 应用程序时,收到 500 错误,导入请求模块的跟踪

问题描述 投票:0回答:1

我已在本地系统中设置了 Next.js Web 应用程序。在尝试登录应用程序时,我收到以下错误,即登录请求 POST http://localhost:3000/api/login 500(内部服务器错误)。

分享下面终端中记录的详细错误详细信息:

 ⚠ ./node_modules/sequelize/lib/dialects/abstract/connection-manager.js
Critical dependency: the request of a dependency is an expression

Import trace for requested module:
./node_modules/sequelize/lib/dialects/abstract/connection-manager.js
./node_modules/sequelize/lib/dialects/mariadb/connection-manager.js
./node_modules/sequelize/lib/dialects/mariadb/index.js
./node_modules/sequelize/lib/sequelize.js
./node_modules/sequelize/lib/index.js
./node_modules/sequelize/lib/index.mjs
./app/utility/db.js
./app/api/login/route.js
 ⚠ ./node_modules/sequelize/lib/dialects/abstract/connection-manager.js
enter code here

我的 postgres 数据库已启动并正在运行,并且用户表包含用户详细信息。有人可以告诉我这里可能有什么问题吗:

版本依赖:

"dependencies": {
    "axios": "^1.7.2",
    "bcryptjs": "^2.4.3",
    "next": "14.2.5",
    "pg": "^8.12.0",
    "pg-hstore": "^2.3.4",
    "postgres": "^3.4.4",
    "react": "^18",
    "react-dom": "^18",
    "sequelize": "^6.37.3"
  },

//app/api/login/route.js

import { sequelize, user } from '../../utility/db';
import { NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';


export async function GET(req) {
  return NextResponse.json({ message: 'GET request received' });
}


export async function post(req) {
  const { email, password } = await req.json();
  
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');

    const foundUser = await user.findOne({ where: { email } });
    if (!foundUser) {
      return NextResponse.json({ message: 'Invalid email or password' }, { status: 401 });
    }

    const passwordMatch = await bcrypt.compare(password, foundUser.password);
    if (!passwordMatch) {
      return NextResponse.json({ message: 'Invalid email or password' }, { status: 401 });
    }

    return NextResponse.json({ message: 'Login successful' });
  } catch (error) {
    console.error('Unable to connect to the database:', error);
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
  }
}

db.js

import { Sequelize, DataTypes } from 'sequelize';

const DB_POOL = {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
const sequelize = new Sequelize('clubdb', 'postgres', 'password_here', {
    host: 'localhost',
    dialect: 'postgres', // or 'postgres' if you're using PostgreSQL
    port: '5432',
  });
  
  const user = sequelize.define('user', {
      id: {
          type: DataTypes.INTEGER(10),
          allowNull: false,
          primaryKey: true,
          autoIncrement: true
      },
      email: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true
      },
      password: {
          type: DataTypes.STRING,
          allowNull: false
      }
  }, {
      timestamps: true,
      tableName: 'user'
  });

// Export the sequelize instance and models
export { sequelize, user };

应用程序/登录/page.js

'use client';
import { useState } from 'react';
import axios from 'axios';
import { useRouter } from 'next/navigation'; // Correct import
import { useAuth } from '../contexts/authContext';

  const Login = () =>{
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const router = useRouter();
  const { dispatch } = useAuth();

  const handleLogin = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('/api/login/', { email, password });
      if (response.status === 200) {
        localStorage.setItem('isAuthenticated', 'true');
        dispatch({ type: 'LOGIN' });
        router.push('/admin');
      }
    } catch (error) {
      setError(error.response?.data?.message || 'Login failed');
    }
    
  };

    return (
        <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
          <h1 className="text-4xl font-bold">Login</h1>
          <form onSubmit={handleLogin} className="mt-4">
            <input
              type="text"
              placeholder="Username"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="border p-2 rounded mb-4"
            />
            <input
              type="password"
              placeholder="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="border p-2 rounded mb-4"
            />
            {error && <p className="text-red-500">{error}</p>}
            <button type="submit" className="bg-blue-500 text-white p-2 rounded">
              Login
            </button>
          </form>
        </div>
      );

  }
  export default Login;

_app.js

import '../styles/globals.css';
import Navbar from './components/navbar';
import { AuthProvider } from './contexts/authContext';

const MyApp = ({ Component, pageProps }) => {
  console.log('Rendering MyApp');

    return (
        <>
        <AuthProvider>
          <Navbar />
          <Component {...pageProps} />
        </AuthProvider>
          
        </>
      );
}

导出默认MyApp;

文件夹结构:

app
│
├── about
│   └── page.js
│
├── admin
│   └── page.js
│
├── api\login
│         └── route.js
│
├── components
│   └── navbar.js
│
├── contexts
│   └── authContext.js
│
├── login
│   └── page.js
│
├── styles
│   └── globals.css
│
├── utility
│   └── db.js
│
└── _app.js
favicon.ico
layout.js
page.js
postgresql next.js sequelize.js
1个回答
0
投票

现在,在我将

sequelize.js
User.js
分开后,错误已经消失并且能够登录系统了。然后我在下面的连接中使用了
DATABASE_URL
dialectModule: pg

/* 实用程序/sequelize.js */

       import * as pg from 'pg';
       import { Sequelize } from 'sequelize';
    
        const DATABASE_URL = 'postgres://username:password@localhost:5432/database_name';
        const sequelize = new Sequelize(DATABASE_URL, {
          dialectModule: pg
        });

    (async () => {
       try {
       await sequelize.authenticate();
       console.log('Database connection successfully established.');
      } catch (error) {
        console.error('Error connecting to the database :', error);
      }
     })();
     export default sequelize;

/* 模型/User.js */

import { DataTypes } from 'sequelize';
import sequelize from '../utility/sequelize';

  const user = sequelize.define('user', {
      id: {
          type: DataTypes.INTEGER(10),
          allowNull: false,
          primaryKey: true,
          autoIncrement: true
      },
      email: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true
      },
      password: {
          type: DataTypes.STRING,
          allowNull: false
      }
  }, {
      timestamps: true,
      tableName: 'user'
  });

  export default user;
© www.soinside.com 2019 - 2024. All rights reserved.