Skip to content
此页目录
本文总阅读量

Vue 跨域代理

代理配置

2.0

js
proxyTable: {
 '/api': {
  target: 'http:// 127.0.0.1:3000/api', // 接口的域名
  // secure: false, // 如果是https接口,需要配置这个参数
  changeOrigin: true, // 如果接口跨域,需要进行这个参数配置,为true的话,请求的header将会设置为匹配目标服务器的规则(Access-Control-Allow-Origin)
  pathRewrite: {
    '^/api': '' // 本身的接口地址没有 '/api' 这种通用前缀,所以要rewrite,如果本身有则去掉 
  }
 }
}

3.0

js
// vue.config.js  脚手架的配置文件
module.exports = {
  // 选项...
  // 配置跨域
  devServer: {
proxy: {
'/api': {
target: 'http:// localhost:3000// api', // 接口的域名
// secure: false, // 如果是 https 接口,需要配置这个参数
changeOrigin: true, // 如果接口跨域,需要进行这个参数配置,为 true 的话,请求的 header 将会设置为匹配目标服务器的规则(Access-Control-Allow-Origin)
pathRewrite: {
'^/api': '' // 本身的接口地址没有 '/api' 这种通用前缀,所以要rewrite,如果本身有则去掉 
}
}
}
  }
}

配置 baseUrl

js
// 与axios同级  axios 引入 {api_url}
// ================== 区分环境,配置接口地址
let host, api_url;
if (process.env.NODE_ENV == "development") { // 开发环境
  host = "http:// localhost:3000",
// api_url = "http:// localhost:3000/api"
api_url = "/api"
}
if (process.env.NODE_ENV == "production") { // 生产环境
  host = "http:// localhost:3000",
api_url = "http:// localhost:3000/api"
}  
export let HOST = host;
export let API_URL = api_url;

评论

交流群