SpringBoot 后端正确配置CORS

这个错误是由于后端没有正确配置CORS(跨源资源共享)。为了允许前端通过浏览器访问后端接口,需要在后端配置CORS。以下是如何在Spring Boot中配置CORS的方法。

在Spring Boot中配置CORS

方法1:全局配置

在Spring Boot应用中,可以通过配置类全局配置CORS。创建一个新的配置类并添加CORS配置。

import org.springframework.context.annotation.Bean;
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:8081")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}
方法2:控制器级别配置

你也可以在具体的控制器方法上配置CORS。添加@CrossOrigin注解到控制器或方法上。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AuthController {

    @CrossOrigin(origins = "http://localhost:8081")
    @PostMapping("/auth/register")
    public ResponseEntity<?> register(@RequestBody UserEntity user) {
        // 注册逻辑
        return ResponseEntity.ok().body("注册成功");
    }
}

完整示例

在Spring Boot应用中,可以同时使用全局和控制器级别的配置。下面是一个完整的示例,包括全局配置和控制器级别的配置。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.http.ResponseEntity;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8081")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

@RestController
public class AuthController {

    @CrossOrigin(origins = "http://localhost:8081")
    @PostMapping("/auth/register")
    public ResponseEntity<?> register(@RequestBody UserEntity user) {
        // 注册逻辑
        return ResponseEntity.ok().body("注册成功");
    }
}

确保前后端端口一致

确保前端代码中的端口与CORS配置中的端口一致。如果前端运行在不同的端口,更新allowedOrigins中的端口号。

前端调用示例

前端代码保持不变,只要后端配置了CORS,前端请求就能成功。

methods: {
    async register() {
        this.$refs.registerFormRef.validate(async valid => {
            if (!valid) return;

            try {
                const response = await this.$http.post('http://localhost:8789/auth/register', this.registerForm);
                const res = response.data;

                if (res.success) {
                    this.$message.success("注册成功!");
                    this.toggleForm(); // 切换回登录表单
                } else {
                    this.$message.error("注册失败!");
                }
            } catch (error) {
                this.$message.error("注册失败!");
            }
        });
    }
}

确保this.$http在你的Vue实例中配置正确,例如使用axios:

import axios from 'axios';
Vue.prototype.$http = axios;

通过这些步骤,可以解决CORS问题,使前端能够成功调用后端的注册接口。

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

繁依Fanyi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值