这个错误是由于后端没有正确配置CORS(跨源资源共享)。为了允许前端通过浏览器访问后端接口,需要在后端配置CORS。以下是如何在Spring Boot中配置CORS的方法。
在Spring Boot中配置CORS
方法1:全局配置
在Spring Boot应用中,可以通过配置类全局配置CORS。创建一个新的配置类并添加CORS配置。
方法2:控制器级别配置
你也可以在具体的控制器方法上配置CORS。添加@CrossOrigin
注解到控制器或方法上。
完整示例
在Spring Boot应用中,可以同时使用全局和控制器级别的配置。下面是一个完整的示例,包括全局配置和控制器级别的配置。
确保前后端端口一致
确保前端代码中的端口与CORS配置中的端口一致。如果前端运行在不同的端口,更新allowedOrigins
中的端口号。
前端调用示例
前端代码保持不变,只要后端配置了CORS,前端请求就能成功。
确保this.$http
在你的Vue实例中配置正确,例如使用axios:
通过这些步骤,可以解决CORS问题,使前端能够成功调用后端的注册接口。