大飞

大飞 关注TA

挑战一切!

大飞

大飞

关注TA

挑战一切!

  •  世界的顶端
  • 混口饭吃
  • 写了333,609字

最近回复

该文章投稿至Nemo社区   Js、Css、Html  板块 复制链接


Vue 跨域请求

发布于 2018/11/29 11:19 1,811浏览 2回复 2,019

   Vue 为了安全,默认不支持跨域请求网络,这就很不方便我们本地调试,但是Vue提供代理配置,如下配置就可以解决跨域问题。

   config/inder.js配置 proxyTable

proxyTable: {
'/api': {
target: 'http://localhost:8002/', //要跨域的接口地址
changeOrigin: true,
pathRewrite: {
'^/api': '' //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://localhost:8002/user/add',直接 写‘/api/user/add’即可
}
}
},

一下以axios网络封装配置为例:

import axios from 'axios'

export default {
handleResp: function (context, resp, resolve, reject) {
console.log(resp.data)
if (resp.data.code === 200) {
resolve(resp.data)
} else if (resp.data.code === 401) {
context.$comUtils.showErrorMessage(context, resp.data.msg)
reject(new Error('Code Error'))
// 失败的话就原地跳转咯
window.location.href = 'http://localhost:8090/' + 'login'
// }
} else if (resp.data.code === 403) {
context.$router.replace({ name: 'NotAuth' })
} else {
context.$comUtils.showErrorMessage(context, resp.data.msg)
reject(new Error('Code Error'))
}
},
commonRequest: function (context, method, url, params) {
return new Promise((resolve, reject) => {
axios({
method: method,
baseURL: '/api/', // 这里就是使用了代理 进行跨域请求
url: url,
params: (method === 'get' ? params : null),
data: (method !== 'get' ? params : null)
})
.then((resp) => {
if (this.handleResp) {
this.handleResp(context, resp, resolve, reject)
} else {
resolve(resp)
}
})
.catch((e) => {
console.log(e)
reject(e)
})
})
},
get: function (context, url, params) {
return this.commonRequest(context, 'get', url, params)
},
post: function (context, url, params) {
return this.commonRequest(context, 'post', url, params)
},
put: function (context, url, params) {
return this.commonRequest(context, 'put', url, params)
},
delete: function (context, url, params) {
return this.commonRequest(context, 'delete', url, params)
}
}
点赞(2)
本文标签
 vue

上一个文章:Android 面试高级技能

下一个文章:Tornado 用户验证

点了个评