配置api接口代理

2021-07-04  本文已影响0人  JX灬君

1.配置api接口代理
参考vue cli3.0文档 devServer.proxy部分
参考代码

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: '<url>',
        ws: true,
        changeOrigin: true
      },
      '/foo': {
        target: '<other_url>'
      }
    }
  }
}

官网文档中说明
》如果你想要更多的代理控制行为,也可以使用一个 path: options 成对的对象。完整的选项可以查阅 http-proxy-middleware]
https://github.com/chimurai/http-proxy-middleware#proxycontext-config
参考代码

// include dependencies
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

// proxy middleware options
const options = {
  target: 'http://www.example.org', // target host
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // proxy websockets
  pathRewrite: {
    '^/api/old-path': '/api/new-path', // rewrite path
    '^/api/remove/path': '/path', // remove base path
  },
  router: {
    // when request.headers.host == 'dev.localhost:3000',
    // override target 'http://www.example.org' to 'http://localhost:8000'
    'dev.localhost:3000': 'http://localhost:8000',
  },
};

// create the proxy (without context)
const exampleProxy = createProxyMiddleware(options);

// mount `exampleProxy` in web server
const app = express();
app.use('/api', exampleProxy);
app.listen(3000);

根据实际情况在本地修改vue.config.js

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: "https://yapi.baidu.com",
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          "^/api": "/mock/74977/api", // rewrite path
        },
      },
    },
  },
};

axios使用方法对比

// old 
this.axios
        .post("https://yapi.baidu.com/mock/74977/api/login", {
          CNO: this.cm_code,
          PNO: this.PNO,
          Passwd: this.Passwd,
        })
        .then((res) => {
         
        })
        .catch((e) => {
          // 登录异常失败
        });
// new
this.axios
        .post("/api/login", {
          CNO: this.cm_code,
          PNO: this.PNO,
          Passwd: this.Passwd,
        })
        .then((res) => {
         
        })
        .catch((e) => {
          // 登录异常失败
        });
上一篇下一篇

猜你喜欢

热点阅读