折腾:
【未解决】vuejs中调用本地localhost的api报错:Access to XMLHttpRequest at from origin has been blocked by CORS policy
期间,去给spring boot的java后端加上CORS支持
java spring boot CORS
1 | import org.springframework.web.bind.annotation.CrossOrigin; |
好像只能允许http://localhost:9000的CrossOrigin
不能全部支持?
直接用:
@CrossOrigin
即可
1 2 3 4 5 6 7 8 9 10 | @RestController @RequestMapping( "/account" ) public class AccountController { @CrossOrigin @GetMapping( "/{id}" ) public Account retrieve(@PathVariable Long id ) { // ... } |
另外可以全局Class级别加上CrossOrigin
1 |
1 2 3 4 5 6 7 8 9 | @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping( "/**" ); } } |
去找找
此处自己的WebConfig
- * 方式1:返回新的CorsFilter
- * 方式2:重写WebMvcConfigurer
- * 方式3:使用注解(@CrossOrigin)
- * 方式4:手工设置响应头(HttpServletResponse )
注:
CorsFilter / WebMvcConfigurer / @CrossOrigin 需要SpringMVC 4.2 以上的版本才支持
对应SpringBoot 1.3 版本以上都支持这些CORS特性
先去试试局部跨域是否有效
有空再试试 全局跨域
此处已有代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @RequestMapping (path = "/iec104" ) / / This means URL's start with / (after Application path) public class IEC104Controller { private static Logger logger = LoggerFactory.getLogger(IEC104Controller. class .getName()); @Autowired / / This means to get the bean called userRepository / / Which is auto - generated by Spring, we will use it to handle the data private IEC104Repository iec104Repository; @PostMapping(path = "/add" ) / / Map ONLY POST Requests / / public @ResponseBody String addNewIEC104 ( public @ResponseBody IEC104 addNewIEC104 ( / / @RequestParam String data / / @RequestParam String data, / / @RequestParam String parseResult @RequestBody Map <String, Object > payload ) { |
有前面提到的@Controller
去加上试试
1 2 3 4 | import org.springframework.web.bind.annotation.CrossOrigin; @Controller / / This means that this class is a Controller @CrossOrigin |
然后重新编译
1 2 | mvn clean package java -jar target /xxx-0 .0.1-SNAPSHOT.jar |
然后再去vuejs中测试,就可以了。
【总结】
此处给java的spring boot的后端添加CORS支持:
是给@Controller加上:@CrossOrigin
1 2 3 4 5 | @Controller / / This means that this class is a Controller @CrossOrigin @RequestMapping (path = "/iec104" ) / / This means URL's start with / (after Application path) public class IEC104Controller { ... |
即可。
关于原理,详见:
转载请注明:在路上 » 【已解决】给java的spring boot中后端加上CORS支持