You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS调用外部API端点失败问题排查

NextJS调用外部API出现400错误问题

问题现象

  • 调用外部API的/favourites/add和/favourites/get-favourites接口时返回AxiosError: Request failed with status code 400错误,错误日志如下:
{"level":50, "Wed Jan 24 2024","pid":4488,"hostname":"DESKTOP-S75IFN7","msg":"AxiosError: Request failed with status code 400
    at settle (webpack-internal:///(rsc)/./node_modules/axios/lib/core/settle.js:21:16)
    at IncomingMessage.handleStreamEnd (webpack-internal:///(rsc)/./node_modules/axios/lib/adapters/http.js:513:81)
    at IncomingMessage.emit (node:events:526:35)
    at endReadableNT (node:internal/streams/readable:1359:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"}
  • Postman调用上述两个接口正常,且/register和/login接口在NextJS中可正常调用。
  • 浏览器控制台报错:GET http://localhost:3000/api/favourites/1 500 (Internal Server Error)

相关代码(NextJS API路由)

import { NextRequest, NextResponse } from "next/server"
import { logger } from "@/utils/logger"
import axios from 'axios'

export const dynamic = 'force-dynamic'

const baseUrl = 'http://127.0.0.1:4000/api/favourites'

export const GET = async (req: NextRequest, route: { params: { userID: number }}) => {
    console.log('Request Method: ', req.method)
    console.log('Params: ', route.params.userID)
    if (req.method === 'GET') {
        try {
            const userID = route.params.userID
            const { data } = await axios.get(`${baseUrl}/get-favourites?user_id${userID}`)
            
            if (data != null) {
                return NextResponse.json({
                    result: data,
                    success: true
                })
            } else {
                return new NextResponse('Failed to get favourites', {
                    status: 400
                })
            }
        } catch (e) {
            if (e instanceof Error) {
                logger.error(`${e.stack}`)
                return new NextResponse('Internal Server Error', {
                    status: 500
                })
            }
        }
    } else {
        return new NextResponse('Not Implemented', {
            status: 405
        })
    }
}

问题原因及解决方法

1. URL参数拼接错误

代码中拼接请求URL时,user_id参数缺少赋值符号=,导致外部API无法识别参数格式,返回400错误。

修正代码:

const { data } = await axios.get(`${baseUrl}/get-favourites?user_id=${userID}`)

2. 路由参数类型处理

NextJS路由参数实际为字符串类型,即使定义为number也需要手动转换,避免参数格式不兼容:

// 转换为数字类型
const userID = Number(route.params.userID)
// 或使用parseInt
const userID = parseInt(route.params.userID.toString(), 10)

3. 错误调试优化

在catch块中捕获Axios的响应错误信息,便于定位问题:

catch (e) {
    if (e instanceof Error) {
        // 打印API返回的具体错误信息
        if ('response' in e) {
            logger.error(`API错误详情: ${JSON.stringify((e as any).response.data)}`)
        }
        logger.error(`${e.stack}`)
        return new NextResponse('Internal Server Error', {
            status: 500
        })
    }
}

内容的提问来源于stack exchange,提问作者SFSA_Despair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:57:39