vue解决跨域路由冲突问题思路解析(2)
然后在main.js 里面引入,这样可以保证动态的匹配生产和开发的定义前缀
import apiConfig from '../config/api.config' import Axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, Axios) Axios.defaults.baseURL = apiConfig.baseUrl
经过上面配置后,在dom里面可以这样轻松的访问,也不需要在任何组件里面引入axios模块了。
logout(){
this.$http.post('/users/logout').then(result=>{
let res = result.data;
this.nickName = '';
console.log(res);
})
},
getGoods(){
this.$http.post('/goods/list').then(result=>{
let res = result.data;
this.nickName = '';
console.log(res);
})
}
最终代码
在代理里面配置
proxyTable: {
'/api/**': {
target: 'http://localhost:3000',
pathRewrite:{
'^/api':'/'
}
},
},
在config里面的api.config.js 配置
在config 文件夹里面新建一个 api.config.js 配置文件
const isPro = Object.is(process.env.NODE_ENV, 'production')
module.exports = {
baseUrl: isPro ? 'http://www.vnshop.cn/api/' : 'api/'
}
关于生产和开发配置不太了解
可以去 dev-server.js 里面看配置代码
const webpackConfig = (process.env.NODE_ENV === 'testing' || process.env.NODE_ENV === 'production') ?
require('./webpack.prod.conf') :
require('./webpack.dev.conf')
在main.js 入口文件里面配置
import apiConfig from '../config/api.config' import Axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, Axios) Axios.defaults.baseURL = apiConfig.baseUrl
在dom里面请求api的姿势
logout(){
this.$http.post('/users/logout').then(result=>{
let res = result.data;
this.nickName = '';
console.log(res);
})
},
getGoods(){
this.$http.post('/goods/list').then(result=>{
let res = result.data;
this.nickName = '';
console.log(res);
})
}
PS:下面通过一段代码学习下vue下跨域设置
1、在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的。
2、当跨域无法请求的时候我们可以修改工程下config文件夹下的index.js中的dev:{}部分。
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: false,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://api.douban.com/v2',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
内容版权声明:除非注明,否则皆为本站原创文章。
