1.解决跨域问题
出现跨域的状况(受浏览器同源策略的影响):前端
解决跨域的方法:vue
1) 前端项目增长跨域代理 在vue.config.js文件中添加
2) 后端增长headerios
二、封装axios
src/config/index.js:axios
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:api
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 } }) }