React前端通过Axios连接Spring后端遇ERR_NETWORK错误求助
解决Axios ERR_NETWORK 连接问题
针对你遇到的React前端调用Spring后端出现的Axios网络错误,以下是几个常见的排查和解决方向:
1. 检查BaseURL协议是否正确
你的api.js中使用了https://localhost:8080,但本地运行的Spring Boot项目默认是HTTP协议(除非你手动配置了SSL证书)。将baseURL改为:
const api = axios.create({ baseURL: "http://localhost:8080" });
2. 解决跨域问题
React默认运行在3000端口,Spring后端在8080端口,属于不同域,浏览器会拦截跨域请求。需要在Spring后端配置CORS:
- 方法一:在Controller类或方法上添加
@CrossOrigin(origins = "http://localhost:3000")注解 - 方法二:全局配置CORS(适用于所有接口),创建配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*"); } }
3. 确认后端服务端口是否匹配
检查Spring Boot的配置文件(application.properties或application.yml),确认server.port确实是8080,没有被修改为其他端口。
4. 测试后端接口可用性
直接在浏览器地址栏访问http://localhost:8080/songs,如果能返回数据,说明后端接口正常;如果无法访问,先排查后端服务是否真的启动成功。
额外排查点
- 检查浏览器开发者工具的「网络」标签,查看请求的具体状态码和错误信息,比如是否是
CORS相关错误,还是真的无法连接服务器 - 确保本地防火墙没有拦截8080端口的请求
内容的提问来源于stack exchange,提问作者vitoriac
相关产品推荐
相关产品推荐

