AxiosError {消息:'网络错误',名称:'AxiosError',代码:'ERR_NETWORK',配置:{...},请求:XMLHttpRequest,...}

vit*_*iac 10 javascript xmlhttprequest reactjs axios

我正在开发一个项目,该项目的前端内置于 React 中,后端内置于 Spring 中,但我似乎无法使用 axios 连接这两个项目。

\n

请记住,后端工作正常(而且我不太擅长反应)。

\n

这是我在控制台收到的错误:

\n
    \n
  1. AxiosError\xc2\xa0{消息:\'网络错误\',名称:\'AxiosError\',代码:\'ERR_NETWORK\',配置:{\xe2\x80\xa6},请求:XMLHttpRequest,\xc2\xa0 \xe2\x80\xa6}

    \n
      \n
    1. 代码:“ERR_NETWORK”

      \n
    2. \n
    3. 配置:{过渡:{\xe2\x80\xa6},transformRequest:数组(1),transformResponse:数组(1),超时:0,适配器:\xc6\x92,\xc2\xa0\xe2\x80\xa6}

      \n
    4. \n
    5. 消息:“网络错误”

      \n
    6. \n
    7. 名称:“Axios错误”

      \n
    8. \n
    9. 请求:XMLHttpRequest\xc2\xa0{数据:未定义,onreadystatechange:null,readyState:4,超时:0,withCredentials:false,\xc2\xa0\xe2\x80\xa6}

      \n
    10. \n
    11. 响应:XMLHttpRequest\xc2\xa0{数据:未定义,onreadystatechange:null,readyState:4,超时:0,withCredentials:false,\xc2\xa0\xe2\x80\xa6}

      \n
    12. \n
    13. [[原型]]:错误

      \n
    14. \n
    \n
  2. \n
\n

这是我的 api.js:

\n
import axios from \'axios\';\n\nconst api = axios.create({\n  baseURL: "https://localhost:8080"\n});\n\nexport default api;\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的 App.js:

\n
import \'./App.css\';\nimport axios from "axios";\nimport {useEffect, useState} from \'react\'\nimport api from \'./api.js\';\n\nfunction App() {\n  const songs = async () => {\n    try{\n      const response = await api.get("/songs");\n    }\n    catch(err) {\n      console.error(err);\n    }\n  };\n  return (\n     <div className="all-page">\n             <main className="central-div">\n                <h2>Taylor\'s Songs</h2>\n                <button type="submit" className="quote-bttn" onClick={songs}>\n                    FIND ME A QUOTE\n                </button>\n                <button type="submit" className="recommend-bttn">\n                    GET ME A RECOMMENDATION\n                </button>\n             </main>\n        </div>\n  );\n \n}\n\nexport default App;\n
Run Code Online (Sandbox Code Playgroud)\n

每当我尝试单击“quote-bttn”按钮时就会出现问题。

\n

如果有人知道如何解决这个问题,我将非常感激!

\n

(另外,如果我遗漏了什么,这是完整的代码:https://github.com/vitoriaacarvalho/my-taylor-swift-api/commit/0276222d35aa9a3fda8033f594d9727feded854b”

\n

Sri*_*h L 4

您似乎使用的是 https 请求,而不是 http。您的基本 URL 意味着您的服务器位于您的本地计算机中。可以使用 http 和 https 访问本地服务器,但如果您确定已配置 SSL 证书来访问 https 请求,请尝试检查后端的 CORS 策略/限制。理想情况下,人们会选择 CORS:“AllowAll”,但您也可以对其进行配置,以便仅从指定的客户端端口接受请求。

  • 这对我帮助很大!谢谢你!对于将来遇到同样问题的人,以下是我使用的代码: public class WebMvcConfig Implements WebMvcConfigurer{ Override public void addCorsMappings(CorsRegistryregistry) {registry.addMapping("/**") .allowedMethods("*") .allowedOrigins("*") .allowedHeaders("*") .allowCredentials(false) .maxAge(86400); } } (3认同)