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

使用Axios调用API时出现404 AxiosError的技术求助

Axios请求404错误排查与解决

错误详情

AxiosError
code: "ERR_BAD_REQUEST"
config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message: "Request failed with status code 404"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta char…re>Cannot GET /discover/tv</pre>\n</body>\n</html>\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}
stack: "AxiosError: Request failed with status code 404\n    at settle (http://localhost:3000/static/js/bundle.js:41933:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:40631:66)"

相关代码

Row.js 文件

import React, { useEffect, useState } from 'react'
import axios from 'axios';
function Row({ title, fetchUrl }) {
    const [movies, setMovies] = useState();
    useEffect(() => {
        async function fetchData() {
            const request = await axios.get(fetchUrl);
            console.log(request);
            return request;
        }
        fetchData();
    }, []);

    return (
        <div>
            <h2>{title}</h2>
        </div>
    )
}

export default Row

axios.js 文件

import axios from "axios";
const instance = axios.create({
    baseURL: "https://api.themoviedb.org/3",
});
export default instance;

原因分析

  1. Axios实例未正确使用:Row.js中导入的是原生axios,而非axios.js里配置了baseURL的自定义实例。请求没有带上https://api.themoviedb.org/3前缀,直接向当前前端域名发送/discover/tv请求,导致404。
  2. 缺少TMDB API密钥:TMDB所有接口请求必须携带api_key参数,即使路径修复后,无密钥也会返回错误。
  3. 未捕获异步错误:fetchData作为async函数,未用try/catch处理请求失败的情况,导致未捕获的Promise错误抛出。

解决方法

  1. 替换Axios导入:在Row.js中导入自定义的axios实例,确保路径与文件目录匹配:
// Row.js 修改导入语句
import axios from './axios';
  1. 添加API密钥:
    方式一:在axios实例中全局配置密钥

    // axios.js
    import axios from "axios";
    const instance = axios.create({
        baseURL: "https://api.themoviedb.org/3",
        params: {
            api_key: "你的TMDB API密钥" // 替换为自己的密钥
        }
    });
    export default instance;
    

    方式二:在单个请求中传入密钥

    // Row.js 的fetchData函数内
    const request = await axios.get(fetchUrl, {
        params: {
            api_key: "你的TMDB API密钥"
        }
    });
    
  2. 捕获请求错误:用try/catch包裹异步请求,避免未捕获错误:

async function fetchData() {
    try {
        const request = await axios.get(fetchUrl);
        console.log(request);
        setMovies(request.data.results); // 记得更新movies状态
    } catch (error) {
        console.error('请求失败:', error);
    }
}
  1. 校验接口路径:确保fetchUrl是TMDB的合法路径,比如/discover/tv是有效路径,若需要额外参数(如language)可按需添加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:01:44