Ajax請求
1.解決跨域問題
出現跨域的情況(受瀏覽器同源策略的影響):
解決跨域的方法:
1) 前端項目增加跨域代理
在vue.config.js文件中添加
2) 後端增加header
2、封裝axios
src/config/index.js:
export const baseURL = process.env.NODE_ENV === 'production'
? 'http://production.com'
: 'http://localhost:3000'
src/lib/axios.js:
import axios from 'axios'
import { baseURL } from '@/config'
class HttpRequest {
constructor (baseUrl = baseURL) { // 如果傳入參數就用傳入的,沒有就用baseURL
this.baseUrl = baseUrl
this.queue = {}
}
getInsideConfig () { // 統一添加請求參數
const config = {
baseURL: this.baseUrl, // axios.create 參數 baseUrl將被添加到`url`前面,除非`url`是絕對的。
headers: {
// 這裏可以添加統一的header 如JWT登錄
// COP_Authorization: 'Bearer ' + getToken()
}
}
return config
}
distroy (url) {
delete this.queue[url]
if (!Object.keys(this.queue).length) {
// Spin.hide()
}
}
interceptors (instance, url) { // 請求、響應攔截
instance.interceptors.request.use(config => { // request請求攔截
// 添加全局的loading...
if (!Object.keys(this.queue).length) { // Object.keys獲取隊列裏的屬性名 如果隊列裏面沒有請求,就添加loading...
// Spin.show()
}
this.queue[url] = true
return config
}, error => {
return Promise.reject(error)
})
instance.interceptors.response.use(res => { // response攔截器
// 統一增加錯誤提示
this.distroy(url)
const { data, status } = res // ES6解構賦值
return { data, status }
}, error => {
this.distroy(url)
return Promise.reject(error)
})
}
request (options) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options) // 合併多個對象
this.interceptors(instance, options.url)
return instance(options) // 執行調用
}
}
export default HttpRequest
src/api/index.js:
import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios
src/api/user.js:
import axios from './index'
export const getUserInfo = ({ userId }) => {
return axios.request({
url: '/getUserInfo',
method: 'post',
data: {
userId
}
})
}