美文网首页
webpack进阶【19】: vue-cli 脚手架环境 反向

webpack进阶【19】: vue-cli 脚手架环境 反向

作者: 岚平果 | 来源:发表于2020-04-30 16:39 被阅读0次

webpack : vue-cli 脚手架环境 代理服务器的配置

注意:本进阶在webpack进阶【18】的基础上进行衍生。

一、vue-cli为什么要进行代理服务器(也叫反向代理)

    1. 在开发环境中,前端浏览器,运行代码,localhost:3000/..., 请求后台服务器: localhost:8080/... 这时候,会有【跨域】的问题出现。
    1. 跨域:域名、端口、协议、不同,就会出现跨哉现象。
    1. webpack 的反向 代理,可以起一个临时的代理服务器,帮助解决在【开发过程中】出现的跨域问题,这时候就能拿到后台的数据了。现在我们在本地发起一个请求试试。

二、安装 axios,发送 ajax 请求

npm i axios -D

三、在 home.vue 中引入 axios ,并 发送 请求

我们要请求 这个网址的数据
http://order.xmvogue.com/word/public/index.php?s=/home/goods/get_off_list

<template>
  <div class="home">
      <div class="box">
          这是一个 home 组件
      </div>
  </div>
</template>

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

export default {
    async created() {
        const url = `/word/public/index.php?s=/home/goods/get_off_list`;
        const res = await axios.get(url)
        console.log(res)
    }
}
</script>
<style lang="less">
    .box{
        font-size: 20px;
        width: 200px;
        height: 200px;
        background: pink;
    }
</style>

四、vue.config.js 代理服务器配置

module.exports = {
    devServer: {
        port: 3000,    // 浏览器打开的端口
        open: true,    // 是否自动打开浏览器
        // 配置代理服务器,进行代理数据
        proxy: {
            // 以后在开发过程中,只要请求的路径,以 /music 开头,都会被代理。
            // 如果 请求时前面加了 /music, 代理也需要加上 /music
            '/': {
                target: 'http://order.xmvogue.com/', // 代理的基础路径
                pathRewrite: {'^/': ''}         // 如果你不想始终传递 /music ,则需要重写路径:
            }
        }
    },
    // rem 的配置
    css: {
        loaderOptions: {
            css: {},
            postcss: {
                plugins: [
                    require('postcss-px2rem') ({
                        // 适配 375 屏幕, 设计图 750 中量出来的尺寸要 除以 2
                        // 配置成 37.5 是为了兼容 没有适配 rem 布局的第三方 ui 库
                        remUnit: 37.5
                    })
                ]
            }
        }
    }
}

五、现在我们重新启动本地开发脚本

npm run serve

六、经过反向代理后,我们能拿到后台的数据。

image.png

七、home.vue 和 vue.config.js 中也可以如下写法

相关文章

网友评论

      本文标题:webpack进阶【19】: vue-cli 脚手架环境 反向

      本文链接:https://www.haomeiwen.com/subject/ieftghtx.html