今天写一个前后端分离的项目发现跨域请求失败发现是有一个注解没有加记录一下
@RestController
public class BookController {
@Resource
private BookRepository bookRepository;
@CrossOrigin//跨域
@RequestMapping("/findAll")
public Object findAll(){
return bookRepository.findAll();
}
}
vue
created() {
axios.get('http://localhost:8081/findAll').then(function (resp) {
console.log(resp);
});
}
当然也可以通过配置类的方法来解决
package com.wyz.config;
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 CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowCredentials(false).maxAge(3600);
}
}