一、设置代理
在vue.config.js中,设置代理,在开发环境中可以避免跨域的问题:
devServer:{
proxy:"www.shmaur.com"
}
二、在服务端设置请求头
res.header('Access-Control-Allow-Origin','*')
res.header('Access-Control-Allow-Headers','X-Requested-With,Content-Type')
res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS')
三、封装
class HttpRequeset {
constructor (baseUrl = baseURL) {
this.baseUrl = baseUrl
}
getInsideConfig () {
const config = {
baseUrl: this.baseUrl,
headers: {
},
timeout: 5000
}
return config
}
interceptors (instance) {
instance.interceptors.request.use(config => {
return config
}, error => {
return Promise.reject(error)
})
instance.interceptors.response.use(res => {
return res
}, error => {
return Promise.reject(error)
})
}
request (options) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options)
this.interceptors(instance)
return instance(options)
}
}
export default HttpRequeset
网友评论