一、问题描述
在开发过程中,和后端交互的时候避免不了有跨域,解决跨域的方法很多,今天聊一聊前端vue项目是如何解决跨域的。
二、问题解决
先提前说明一下 下面提的这些方法只是配置不一样,但原理都一样。
- target是你要代理的域名,必须要加上http。
- changeOrigin必须为true
- 封装的axios中的baseUrl引号的内容是最终要拼接到你要访问的url上的
- proxy里引号的内容匹配的就是request中的baseUrl引号的内容
废话不多说,直接上代码看怎样配置 1、第一种
module.exports = {
devServer: {
port: 9528,
open: true,
host: '0.0.0.0',
proxy: {
'': {
target: 'http://34.101.146.229:8888',
changeOrigin: true,
pathRewrite: {
"^''": ""
}
}
},
},
}
封装的axios里的代码的baseUrl这样写,省略其它无关紧要代码
const instance = axios.create({
baseURL: '',
timeout: 10000
})
封装请求接口的函数 
比如我要现在访问 http://localhost:9528/device/share?page=1&limit=10 当代码执行的时候, 首先用http://34.101.146.229:8888 代替http://localhost:9528 然后遇到空字符串用空字符串代替,或者直接默认 所以此时变为 http://34.101.146.229:8888 再拼接上 '/device/share?page=' + page + '&limit=' + limit' 就相当于访问 'http://34.101.146.229:8888/device/share?page=' + page + '&limit=' + limit
2、第二种
module.exports = {
devServer: {
port: 9528,
open: true,
host: '0.0.0.0',
proxy: {
'/': {
target: 'http://34.101.146.229:8888',
changeOrigin: true,
pathRewrite: {
"^/": ""
}
}
},
},
}
封装的axios里的代码的baseUrl这样写,省略其它无关紧要代码
const instance = axios.create({
baseURL: '/',
timeout: 10000
})
封装请求接口的函数 
比如我要现在访问 http://localhost:9528/device/share?page=1&limit=10 当代码执行的时候, 首先用http://34.101.146.229:8888 代替http://localhost:9528 然后遇到“/”用空字符串代替 所以此时变为 http://34.101.146.229:8888 再拼接上 '/device/share?page=' + page + '&limit=' + limit' 就相当于访问 'http://34.101.146.229:8888/device/share?page=' + page + '&limit=' + limit
看一下实际操作的结果截图  3、第三种
module.exports = {
devServer: {
port: 9528,
open: true,
host: '0.0.0.0',
proxy: {
'/api': {
target: 'http://34.101.146.229:8888',
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
}
},
},
}
封装的axios里的代码的baseUrl这样写,省略其它无关紧要代码
const instance = axios.create({
baseURL: '/api',
timeout: 10000
})
封装请求接口的函数 
比如我要现在访问 http://localhost:9528/api/device/share?page=1&limit=10 当代码执行的时候, 首先用http://34.101.146.229:8888 代替http://localhost:9528 然后遇到“/api”用空字符串代替 所以此时变为 http://34.101.146.229:8888 再拼接上 '/device/share?page=' + page + '&limit=' + limit' 就相当于访问 'http://34.101.146.229:8888/device/share?page=' + page + '&limit=' + limit
看一下实际操作的结果截图  4、第四种 
封装的axios里的代码的baseUrl这样写,省略其它无关紧要代码

封装请求接口的函数 
比如我要现在访问 http://localhost:9528/api/device/share?page=1&limit=10 当代码执行的时候, 首先用http://34.101.146.229:8888 代替http://localhost:9528 然后遇到“/api/”用空字符串代替 所以此时变为 http://34.101.146.229:8888 再拼接上 '/device/share?page=' + page + '&limit=' + limit' 就相当于访问 'http://34.101.146.229:8888/device/share?page=' + page + '&limit=' + limit
看一下实际操作的结果截图  5、第五种 这种情况比较特殊       如果有生产环境和开发环境之分,需要使用vue的环境变量 因为生产环境不会使用devserver的东西 
|