ajax 请求
2019-05-22 本文已影响0人
YM雨蒙
Vue开发中解决跨域问题
// vue.config.js
module.exports = {
// 解决跨域 ①
devServer: {
// 把所有的接口代理到目标 url 下
proxy: 'http://localhost:8080'
}
}
// 解决跨域 ② 后端解决
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')
Axios 配置请求拦截
// url.js
// baseURL
export const baseURL = process.env.NODE_ENV === 'production'
? 'http://api.production.com' // 生产 url
: '' // 本地 url 配置了前端代理 ? '' : 'http://localhost:xxxx'
// axios.js
import axios from 'axios'
import { baseURL } from './url.js'
class HttpRequest {
constructor (baseUrl = baseURL) { // 设置默认值
this.baseUrl = baseUrl
this.quene = {} // 队列
}
getInsideConfig () {
const config = {
baseUrl: this.baseUrl,
headers: {
// ...
}
}
return config
}
// 拦截器
interceptors (instance, url) {
instance.interceptors.request.use(config => {
// 添加全局的loading
if (!Object.keys(this.quene).length) {
// Spin.show() loading
}
return config
}, error => {
return Promise.reject(error)
})
instance.interceptors.response.use(res => {
delete this.quene[url]
console.log(res)
const { data, status } = res
return { data, status }
}, err => {
delete this.quene[url]
return Promise.reject(err)
})
}
request (options) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options) // 合并到一个对象中
this.interceptors(instance, options.url)
return instance(options)
}
}
export default HttpRequest
// index.js
import { HttpRequest } from './axios'
const axios = new HttpRequest()
export default axios
// user.js
import axios from './index'
export const getUserInfo = ({ userId }) => {
return axios.request({
url: '/getUserInfo',
method: 'post',
data: {
userId
}
})
}
// home.vue
<script>
import { getUserInfo } from './user.js'
export default {
methods: {
getInfo() {
getUserInfo({ userId: '1' }).then(res => {
console.log(res)
})
}
}
}
</script>