Next.js+TypeScript自定义认证系统Axios请求返回500错误排查
自定义Next.js+TypeScript认证系统注册接口500错误排查
我正在使用Next.js和TypeScript搭建自定义认证系统(不使用NextAuth),向注册端点发送包含username和password的对象时,收到了500状态码错误。
前端提交表单代码
<form className="space-y-6" onSubmit={(e) => handleSubmit(e)}> <Input id='username' label='Username' disabled={isLoading} type='text' placeholder='Enter your username' state={username} setState={setUsername}/> <Input id='password' label='Password' disabled={isLoading} type='password' placeholder='Enter your password' state={password} setState={setPassword}/> {aOption !== aOptions.LOGIN ? <Input id='password' label='Password' disabled={isLoading} type='password' placeholder='Confirm the password' state={rePassword} setState={setRePassword}/> : null} <Button disabled={isLoading} action={aOption === aOptions.LOGIN ? 'Sign In' : 'Sign Up'}/> </form>
表单提交触发的handleSubmit函数
type AuthType = { username: string, password: string, }; const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); setIsLoading(true); const data = { username: username, password: password }; if(aOption === aOptions.REGISTER) { if(password === rePassword){ axios.post('/api/register', data) .then(function (response) { console.log(response); setIsLoading(false); }) .catch(function (error) { console.log(error); setIsLoading(false); }); } else { // 建议用状态管理显示错误,而非throw(throw会导致未捕获错误) // throw new Error("The passwords don't match") setError("密码不匹配"); setIsLoading(false); } } else { } };
注册端点原代码
type AuthType = { username: string, password: string, }; export async function POST(data: AuthType){ console.log(data); //return data; }
收到的错误信息
POST http://localhost:3000/api/register 500 (Internal Server Error) AuthForm.tsx:50 AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} code: "ERR_BAD_RESPONSE" config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message: "Request failed with status code 500" name: "AxiosError" request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response: {data: '', status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …} stack: "AxiosError: Request failed with status code 500 at settle (webpack-internal:///(app-pages-browser)/./node_modules/axios/lib/core/settle.js:24:12) at XMLHttpRequest.onloadend (webpack-internal:///(app-pages-browser)/./node_modules/axios/lib/adapters/xhr.js:121:66)" [[Prototype]]: Error
问题原因及修复方案
核心问题
- Next.js API路由POST函数必须返回合法Response:原代码没有返回任何响应,服务器无法生成有效回复,直接触发500错误。
- 请求体解析方式错误:App Router的API路由POST函数参数是
Request对象,而非直接的请求体数据,需要手动解析JSON内容。
修正后的注册端点代码
import { NextResponse } from 'next/server'; type AuthType = { username: string; password: string; }; export async function POST(request: Request) { try { // 解析请求体JSON数据 const data: AuthType = await request.json(); console.log('收到注册请求:', data); // 这里添加实际注册逻辑:比如密码加密、写入数据库等 // 示例:假设注册成功 return NextResponse.json( { success: true, message: '注册请求已处理' }, { status: 200 } ); } catch (error) { // 处理请求解析失败或其他异常 return NextResponse.json( { success: false, error: '请求格式错误' }, { status: 400 } ); } }
前端补充优化
- 在
handleSubmit的成功/失败回调中重置isLoading状态,避免按钮一直处于加载状态。 - 密码不匹配时,用状态变量显示错误提示,而非直接
throw(throw会导致未捕获的同步错误)。
内容的提问来源于stack exchange,提问作者atryknaav
相关产品推荐
相关产品推荐

