Vue configuration proxy server

install axios

npm i axios

 Introduce axios where you need to use axios

import axios from 'axios'

Configure in methods

Example: request 

http://localhost:5000/students (method 1)

http://localhost:5000/api/students (method 2),

<script>

    import axios from 'axios'

    export default {

        name:'App',

        methods: {

          setStudents(){

            axios.get('http://localhost:8080/api/students').then(

              response => {

                console.log('请求成功了',response.data)

              },

              error => {

                console.log('请求失败了',error.message)

              }

            )

          }

        },

    }

</script>

 

Configure proxy server (configured in vue.config.js)

Method 1: Advantages: Simple configuration, when requesting resources, send them directly to the front end (8080)

              Disadvantages: Only one proxy can be configured, and it is not possible to flexibly control whether the request goes through the proxy

             Working method: When a resource that does not exist in the front-end is requested, the request will be forwarded to the server (matching front-end resources first)

devServer:{

    proxy:'http://localhost:5000'

 },

Method 2: Advantages: Multiple proxies can be configured, and it is possible to flexibly control whether requests go through proxies

               Disadvantages: The configuration is slightly cumbersome, and a prefix must be added when requesting resources

              When changeOrigin is true, the host in the request header received by the server is: localhost:5000

              When changeOrigin is false, the host in the request header received by the server is: localhost:8080

devServer: {

    proxy: {

      '/api': {  //匹配所有以/api开头的路径

        target: 'http://localhost:5000', //代理目标的基础路径

        pathRewrite:{'^/api':''} //修改最终路径删除/api

        // ws: true, //用于支持websocket

        // changeOrigin: true //用于控制请求头中的host值

      },

      '/demo': {

        target: 'http://localhost:5001',

        pathRewrite:{'^/demo':''}

      },

    }

  }

Guess you like

Origin blog.csdn.net/weixin_56868125/article/details/128169957