vue脚手架配置代理

方法一

​ 在vue.config.js中添加如下配置:

devServer:{
  proxy:"http://localhost:5000"
}

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

方法二

Vue2 配置参考:
https://cli.vuejs.org/zh/config/#devserver-proxy

​ 编写vue.config.js配置具体代理规则:

module.exports = {
    devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api1': ''}
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

笔记

如果大家不想用我下面源码提供的网址返回的内容,而是想跟着视频内容用到的两个文件,我根据视频内容(视频位置13:23),写了server1.js。

server1.js

097_配置代理_方式二 - 图1


我写到这里:

// server1.js
const express = require('express')
const app = express()

app.use((request, response, next) => {
    console.log('有人请求服务器1了');
    console.log('请求的资源是:', request.url);
    console.log('请求来自于', request.get('Host'));
    next()
})

app.get('/students', (request, response) => {
    const students = [
        { id: '001', name: 'tom', age: 18 },
        { id: '002', name: 'jerry', age: 19 },
        { id: '003', name: 'tony', age: 120 }
    ]
    response.send(students)
})

app.listen(5000, (err) => {
    if (!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students')
})

启动server1:

node server1

重要源码

vue.config.js

//如何使用,参考官网 https://cli.vuejs.org/zh/config/ 
//该文件最终输送给 webpack(基于 Node.js, 而Node.js采用的是 CommonJS) 

const { defineConfig } = require('@vue/cli-service')
//暴露方式: CommonJS
module.exports = defineConfig({
  transpileDependencies: true,

  pages:{
    index:{
      //入口
      entry:'src/main.js',
    },
  },
  lintOnSave:false, //关闭语法检查

  //开启代理服务器 
  //方式1:
  /*devServer:{
    //proxy: 'http://localhost:5000'
    //注意:只能配置一个代理
    proxy: 'https://asciim.cn/'
  }*/
  //方式2: 官网
  devServer:{
    //注意:每次修改完本文件,都需要退出,重新启动 npm run serve
    proxy: {
      //请求前缀作用: 如果请求的前缀有 /softool ,则走代理。 没有该前缀,就不走代理(访问实际请求url)
      '/softool' :{
        target: 'https://asciim.cn/m/json/000_test_proxy_server/',
        pathRewrite:{'^/softool':''}, //将 /softool 字符串替换为 空

        //ws:true, //用于支持 websocket通讯方式 默认为true

        //用于控制请求头中的 host值
        changeOrigin:true //表示代理服务器 告诉 target服务器,我来自哪里(host字段). false-不说谎 true-说谎模式 默认为true
      },

      //配置多个代理
      '/atguigu' :{
        target: 'https://asciim.cn/m/json/000_test_proxy_server/',
        pathRewrite:{'^/atguigu':''}, 
        //ws:true,
        //changeOrigin:true
      },
    }
  }
})

App.vue

<template>
    <div>
        <button @click="getStudents">获取学生信息</button>

        <button @click="getCars">获取汽车信息</button>
    </div>
</template>

<script>
    //引入 axios
    import axios from 'axios'

    export default {
        name:'App',

        methods:{
            getStudents(){
                axios.get('http://localhost:8080/softool/students.json').then( //给2个回调:成功回调+失败回调
                    response => { //如果成功了,就输出
                        console.log('请求成功了',response.data)
                    },
                    error => {
                        console.log('请求失败了',error.message)
                    }
                )
            },
            getCars(){
                axios.get('http://localhost:8080/atguigu/cars.json').then( //给2个回调:成功回调+失败回调
                    response => { //如果成功了,就输出
                        console.log('请求成功了',response.data)
                    },
                    error => {
                        console.log('请求失败了',error.message)
                    }
                )
            }
        }
    }
</script>