为什么 Axios 在使用 Vite 使用 React 时从 API 返回的数据为“未定义”?

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

作为项目的一部分,我正在使用 Axios 获取与电影相关的数据。但是,当我执行 console.log(response.data) 时,它会返回 HTML 文档形式的内容。当我直接访问该链接时,它会生成 JSON 格式的数据。我该如何解决这个问题?

1)主要代码:

import { useEffect, useState } from 'react';
import './Banner.css' 
import requests from './Requests';
import axios from './Axios'

function Banner() {

    const [movie, setMovie] = useState([]);

    useEffect(() => {
        let fetchData = async () => {
            let response = await axios.get(requests.fetchPopular);
            console.log(response.data);

        }
        fetchData();
    }, []);`

2)Axios.jsx代码:

import axios from "axios";

const instance = axios.create({
     baseURL: "​https://api.themoviedb.org/3"
});

export default instance`

Requests.jsx代码:

const API_KEY = "**************************";
const requests = {
    fetchPopular: `​​/movie/popular?api_key=${API_KEY}`
};
export default requests;

console.log(response.data)的输出:

<!doctype html>
<html lang="en">
  <head>
    <script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx?t=1709691322963"></script>
  </body>
</html>

我试图使用 Axios 以对象形式检索数据,但是,即使当我直接访问链接时,API 似乎正在工作,我收到的数据却是“未定义”。

javascript reactjs api axios
1个回答
0
投票

headers: {accept: 'application/json'}
,您必须为请求设置标头。您可以参考API文档这里

对于 Axios,标题应该是

headers: {
        'Content-Type': 'application/json'
    }
© www.soinside.com 2019 - 2024. All rights reserved.