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

前端与Spring Boot应用API连接报错:Uncaught TypeError问题求助

问题分析与解决方案

错误根源

控制台报错Uncaught TypeError: Cannot read properties of undefined (reading 'post'),本质是user-service.js中导入的myAxios对象未被正确初始化,调用.post()方法时触发了undefined的属性读取错误。

排查与修复步骤

1. 检查helper.js的axios实例配置

你导入的myAxios来自./helper,必须确保该文件正确创建并配置了axios实例:

// helper.js 正确配置示例
import axios from 'axios';

// 创建自定义axios实例,替换为你的Spring Boot服务地址
export const myAxios = axios.create({
    baseURL: 'http://localhost:8080', // 对应Spring Boot服务的端口,默认8080
    headers: {
        'Content-Type': 'application/json'
    }
});
  • 确认baseURL与Spring Boot应用的实际运行地址一致
  • 确保已安装axios依赖:执行npm install axios或yarn add axios

2. 验证导入路径正确性

检查user-service.js中的导入语句:

import { myAxios } from "./helper";
  • 若helper.js和user-service.js不在同一目录,需调整相对路径(比如../helper)

3. 临时替代方案(可选)

如果暂时无法配置myAxios,可以直接在user-service.js中使用原生axios:

import axios from 'axios';

export const signUp = (user) => {
    return axios
    .post("http://localhost:8080/api/v1/auth/register", user)
    .then((response) => response.data);
};

但推荐使用自定义axios实例,便于后续统一配置拦截器、请求头等。

4. 检查Spring Boot服务状态

  • 确保Spring Boot应用正在运行,且/api/v1/auth/register接口可用(可通过Postman测试)
  • 若存在跨域问题,需在Spring Boot中配置CORS:
// Spring Boot CORS配置示例
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000") // 你的React应用地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:20:26