最近闲暇想搞一个博客,于是打算vue+element+springboot。
写到前后端交互的时候一直会报错误。后台路径一直访问不到。
打开控制台查看报错信息
Failed to load http://localhost:8888/console/good/front/classList:
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:8081’ is therefore not allowed access. If an opaque response serves your needs
发现因为是同源得浏览器会产生跨域得问题
前端使用了Vue的axios
所以解决问题需要在前端和后台都配置一下
配置如下:
新建一个js文件
import axios from 'axios'
import qs from 'qs'
// request拦截器
axios.interceptors.request.use(
config => {
// loading
// console.log('loadding')
return config
}, error => {
// Do something with request error
console.log(error) // for debug
return Promise.reject(error)
})
// respone拦截器
axios.interceptors.response.use(response => {
return response
}, error => {
return Promise.resolve(error.response)
})
function checkStatus (response) {
// loading
// 如果http状态码正常,则直接返回数据
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
return response
// 如果不需要除了data之外的数据,可以直接 return response.data
}
// 异常状态下,把错误信息返回去
return {
status: -404,
msg: '网络异常'
}
}
function checkCode (res) {
// 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
if (res.status === -404) {
console.log(res.msg)
}
if (res.data && (!res.data.success)) {
// alert(res.data.error_msg)
}
// console.log('loadding')
return res
}
export default {
post (url, data) {
return axios({
method: 'post',
baseURL: process.env.BASE_API,
url,
data: qs.stringify(data),
timeout: 15000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
},
upload (url, data) {
return axios({
method: 'post',
baseURL: process.env.BASE_API,
url,
data,
timeout: 15000,
headers: {
// 'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'multipart/form-data'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
},
get (url, params) {
return axios({
method: 'get',
baseURL: process.env.BASE_API,
url,
params, // get 请求时带的参数
timeout: 15000
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
}
}
需要用到ajax向后台请求数据的时候
import fecth from 'utils/fecth.js'
//URL 是你后台方法的地址
fecth.post(URL, {
username: this.username,
password: this.password
}).then((res) => {
//res就是后台方法返回的结果
if (res.data.code === '1') {
} else {
this.$msg(res.data.msg)
}
}, (err) => {
alert(`数据请求错误: ${JSON.stringify(err)}`)
})
后台SpringBoot的方法
后台新增一个配置类
实现WebMvcConfigurer的addCorsMappings方法
支持跨域
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Author helloc
* @Date 2019/7/2 19:48
* @Version 1.0
*/
@Configuration
public class VueConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
}
这样配置完 就大功告成啦~~~~~~~~~~~