zoukankan      html  css  js  c++  java
  • vue-cli跨域配置请求API接口

    在使用vue-cli开发项目时难免会需要用到接口数据,最近在写vue-cli项目时就遇到了一些问题,在此记录一下。
    我使用的vue-cli版本是@vue/cli 4.5.13

    一. vue-cli项目的跨域

    在本地开发vue-cli项目时会需要用到后台接口api服务器地址。主要是请求api获取数据展示到前台。

    (一). 配置

    只需要在vue-cli项目下创建一个vue.config.js文件即可,内容如下:

    module.exports = {
      devServer: {
        disableHostCheck: true,
        https: false, // 是否使用`https`协议。
        open: true, // 是否运行完成自动弹出浏览器界面。
        hotOnly: false, // 是否开启热更新。
        proxy: {
          "/api": {
            target: "http://192.168.x.xx:9516/", // 你的API服务器地址
            ws: true, // 代理websockets
            changeOrigin: true,
            pathRewrite: { "^/api": "" }, // 这里会重写请求的接口路径 比如 '/api/bbb/ccc' 重写为 '/bbb/ccc'
          },
        },
      },
    };
    

    (二). 用法

    假设api后端的接口是http://192.168.x.xx:9516/v1/users。那么在vue-cli项目只需要请求类似http://192.168.x.xx:9516/api/v1/users这样的接口即可访问到http://192.168.x.xx:9516/v1/users这个后端接口了。只需要在域名后面加入/api即可。如下示例:

    <template>
      <button @click="get_money">{{ msg }}</button>
    </template>
    
    <script>
    export default {
      data() {
        return {
          msg: '点击',
          money: '20',
        };
      },
    
      methods: {
        get_money() {
          this.$axios
            .post("/api/user/user_money", {
              params: {
                money: this.money,
              }
            })
            .then((res) => {
              console.log(res);
            })
            .catch((err) => {
              console.log(err);
            });
        }
      }
    };
    </script>
    

    一切皆往事在此祝福您生活愉快。如果本文解决了您的问题,麻烦点一下赞。好让往事知道此文有用。

  • 相关阅读:
    POJ 1887 Testing the CATCHER
    HDU 3374 String Problem
    HDU 2609 How many
    POJ 1509 Glass Beads
    POJ 1458 Common Subsequence
    POJ 1159 Palindrome
    POJ 1056 IMMEDIATE DECODABILITY
    POJ 3080 Blue Jeans
    POJ 1200 Crazy Search
    软件体系结构的艺术阅读笔记1
  • 原文地址:https://www.cnblogs.com/zhenzi0322/p/14861993.html
Copyright © 2011-2022 走看看