Springboot+Vue前后端分离实现跨域问题
在IDEA后端新建一个config-》CrosConfig
直接复制粘贴一下的代码:
@Configuration
public class CrosConfig implements WebMvcConfigurer {
//解决跨域问题
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
具体如下:
如果未解决跨域问题会出现如下代码块:
Access to XMLHttpRequest at 'http://localhost:8181/book/findAll' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
如果解决了跨域问题 如下: 没有红色字样
如果你使用Vue中的axios有些问题 那么巧了:
‘axios is not defined’
// axios.get('http://localhost:8181/book/findAll').then(function (resp) {
// _this.books=resp.data
如果用axios.get会出错 那么换第二个红色框的写法 顺序如下
main.js加上这两句:
import axios from 'axios';
Vue.prototype.$axios = axios;
.Vue文件中改用这种写法
this.$axios.get('http://localhost:8181/book/findAll ').then(function (resp) {
到这 问题解决完了~