Vue 设置 Proxy 跨域
.env
VUE_APP_API = "/api"
VUE_API_DEV_TARGET = "http://127.0.0.1:3000"
在 package.json 同级目录下新建 vue.config.js
module.exports={
devServer: {
proxy: {
[process.env.VUE_APP_API]: {
target: process.env.VUE_API_DEV_TARGET, //API服务器的地址
changeOrigin: true,
pathRewrite: {
[`^${process.env.VUE_APP_API}`]: ''
}
}
}
},
}
//设置完成后重启npm
封装 axios.js
@/lib/axios.js
import axios from 'axios'
//判断是否开发环境
export const baseURL = process.env.VUE_APP_API
class HttpRequest {
constructor(baseUrl = baseURL) {
this.baseUrl = baseUrl
this.queue = {}
}
getInsideConfig() {
const config = {
baseURL: this.baseUrl,
headers: {
//
}
}
return config
}
interceptors(instance, url) {
instance.interceptors.request.use(config => {
// 添加全局的loading...
// if (!Object.keys(this.queue).length) {
// Spin.show() 如果存在请求则等待 loading...
// }
this.queue[url] = true
return config
}, error => {
return Promise.reject(error)
})
instance.interceptors.response.use(res => {
const {data} = res
return data
}, error => {
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
@/api/index.js
import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios
@/api/user.js
import axios from '@/lib/axios.js'
export function getUserInfo(data){
return axios.request({
url:'/getUserInfo',
method:'get',
data
})
}
@/views/index.vue
import {getUserInfo} from '@/api/user.js'
export default{
methods:{
async getInfo(){
const res = await getUserInfo({ id:1 })
console.log(res)
}
}
}
node
const express = require('express')
const app = express()
app
.get('/getUserInfo',(req,res)=>{
res.send({ name:'zhansan' })
})
.listen(3000)
webpack 跨域
webpack.config.js
module.exports={
devServer:{
proxy:{
"/api":{
target:'http://127.0.0.1:3000', // 跨域的地址
changeOrigin:true
}
}
}
}
之后就可以跨域请求了
import axios from 'axios'
axios.get('/api').then(res=>console.log(res))