我正在开发一个项目,该项目的前端内置于react,后端内置于spring,我似乎无法使用axios连接它们两个。
请记住,后端工作正常(而且我不太擅长反应)。
这是我在控制台上遇到的错误:
AxiosError {消息:'网络错误',名称:'AxiosError',代码:'ERR_NETWORK',配置:{...},请求:XMLHttpRequest,...}
代码:“ERR_NETWORK”
config:{过渡:{…},transformRequest:数组(1),transformResponse:数组(1),超时:0,适配器:f,…}
消息:“网络错误”
名称:“AxiosError”
请求:XMLHttpRequest {数据:未定义,onreadystatechange:null,readyState:4,超时:0,withCredentials:false,...}
响应:XMLHttpRequest {数据:未定义,onreadystatechange:null,readyState:4,超时:0,withCredentials:false,...}
[[原型]]:错误
这是我的 api.js:
import axios from 'axios';
const api = axios.create({
baseURL: "https://localhost:8080"
});
export default api;
这是我的App.js:
import './App.css';
import axios from "axios";
import {useEffect, useState} from 'react'
import api from './api.js';
function App() {
const songs = async () => {
try{
const response = await api.get("/songs");
}
catch(err) {
console.error(err);
}
};
return (
<div className="all-page">
<main className="central-div">
<h2>Taylor's Songs</h2>
<button type="submit" className="quote-bttn" onClick={songs}>
FIND ME A QUOTE
</button>
<button type="submit" className="recommend-bttn">
GET ME A RECOMMENDATION
</button>
</main>
</div>
);
}
export default App;
每当我尝试单击“quote-bttn”按钮时,问题就会出现。
如果有人知道如何解决这个问题,我将非常感激!
(另外,如果我遗漏了什么,这是完整的代码:https://github.com/vitoriaacarvalho/my-taylor-swift-api/commit/0276222d35aa9a3fda8033f594d9727feded854b“)
您似乎使用的是 https 请求,而不是 http。您的基本 URL 意味着您的服务器位于您的本地计算机中。可以使用 http 和 https 访问本地服务器,但如果您确定已配置 SSL 证书来访问 https 请求,请尝试检查后端的 CORS 策略/限制。理想情况下,人们会选择 CORS:“AllowAll”,但您也可以对其进行配置,以便仅从指定的客户端端口接受请求。
如果你在本地尝试,cors 并不重要。您需要确保您指向后端的正确端点 URL。
例如,如果您的端点 URL 在后端是
http://localhost:5000/api
,而从前端您指向 http://localhost:5000/api2
,则此拼写错误将导致 axios 出现“网络错误”。
我不知道到底为什么,但我的情况的问题是我没有在测试块内渲染组件,而是在描述中渲染组件。
----错-----
describe("", ()=> {
render(<Component />);
test("", () => {
})
})
---- 正确-----
describe("", ()=> {
test("", () => {
render(<Component />);
})
})
尝试在 API 中启用 CORS。