前端vue的端口是8080,vue-cli版本为4.5.9, springboot的端口是8001,前台登录调用后台验证的时候,发生跨域请求,导致无法成功访问,在网上找了一些方式,好多没有成功,这里记录一下:
错误如下:
- Access to XMLHttpRequest at ‘http://localhost:8001/system/login’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
成功的解决方案:
两种方式:
第一种方式:在controller层添加注解
在controller层类上添加 @CrossOrigin
注解
@RestController
@CrossOrigin
@RequestMapping(value = "system")
@Api(value = "登录接口")
public class LoginController {
}
第二种方式:
在springboot的启动类上添加 @CrossOrigin
注解
@SpringBootApplication
@CrossOrigin
public class AdminApp {
public static void main(String[] args) {
SpringApplication.run(AdminApp.class, args);
}
}
然后增加配置类:
@Configuration
public class CrossConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
这里也记录一下无效的解决方案:
- 在vue.config.js 中添加proxy。
module.exports = {
lintOnSave: false,
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8001/',
changeOrigin: true,
}
}
}
}
- 只增加一个
@CrossOrigin
注解,无效