vue3与后端交互请求跨域解决

背景

起的新项目页面登录第一个接口和后端做交互的时候,请求一直打不过去,报错如下:

1
Access to XMLHttpRequest at 'https://iflybudstest.iflytek.com/iflybudsERP/login/auth' (redirected from 'http://192.168.3.9:3002/api/login/auth') from origin 'http://192.168.3.9:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

IMAGE
IMAGE
IMAGE

大概意思是浏览器不允许跨域,然后用chrome查看浏览器的请求,发现请求内容缺少太多

解决办法

在自己的vue项目中配置如下:

login.vue

1
2
3
4
5
6
7
8
9
10
this.$http({
url: '/api/login/auth',
method: 'post',
data: {
username: 'admin',
password: '123456'
}
}).then(res => {
console.log('res', res);
})

axios.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Vue from 'vue'
import axios from 'axios'

const instance = axios.create({
timeout: 10000,
headers: {
'Content-Type': "application/json;charset=utf-8"
}
});
//axios.defaults.baseURL = '/api'

Vue.prototype.$http = axios;

// Vue.use(axios)

export default {
install(Vue){
Object.defineProperty(Vue.prototype,'$http',{value:axios})
}
}

vue.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
module.exports = {
lintOnSave: false,
devServer: {
//port: 3001,
proxy: {
'/api': {
target: 'https://iflybudstest.iflytek.com/iflybudsERP/',
changeOrigin: true,
ws:true,
pathRewrite: {
'^/api': ''
}
}
}
},
productionSourceMap: false,

一开始总是找不到原因,加上了 changeOrigin: true 还是不对,最后把当前的访问地址用ie打开后,发现报错和请求和再chrome中完全不一样,截图忘记截了
然后百度那个问题发现是协议不同导致的跨域问题,只需要在vue.config.js中配置https为true即可,最终版如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
module.exports = {
lintOnSave: false,
devServer: {
//port: 3001,
https:true, // here
proxy: {
'/api': {
target: 'https://iflybudstest.iflytek.com/iflybudsERP/',
changeOrigin: true,
ws:true,
pathRewrite: {
'^/api': ''
}
}
}
},
productionSourceMap: false,
}

关于跨域:
哪些不同会出现跨域: 域名,端口,协议,这里是协议不同,http访问https出现了协议不同的跨域