vue中配置proxy代理

vue中配置proxy代理

  • 如果你的前端应用和后端 API 服务器没有运行在同一个主机上(即解决跨域问题,用proxy代理请求一下),你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

  • 在这里插入图片描述
    转发到

     https://apimusic.linweiqin.com
    

app.vue文件

<template>
  <div id="app">
    <h1>hello Vue clih1>
    <HelloWorld>HelloWorld>
  div>
template>

<script>
/* @ => src */
// import HelloWorld from "./components/HelloWorld.vue";
import HelloWorld from "@/components/HelloWorld.vue";
/* 1. 引入 axios 请求库 */
import axios from "axios";
/* 组件的配置项 */
export default {
  created() {
    // axios
    //   .get("song/url?id=504835560")
    //   .then((res) => {
    //     console.log(res);
    //   });
    axios
      .get("/song/url?id=504835560")
      .then((res) => {
        console.log(res);
      });
    axios.get("/api/s/getHotProducts").then(res=>{
      console.log(res);
    })
    
  },
  name: "App",
  components: {
     HelloWorld
  },
};
script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
style>

在 vue.config.js 文件中添加如下所示的配置项

module.exports = {
  lintOnSave: false,
  devServer: {
    proxy: "https://apimusic.linweiqin.com/"
  }
};

如果请求有多个不同的地址

A: http://s.linweiqin.com/api/s/getHotProducts

B: https://apimusic.linweiqin.com/song/url?id=504835560

module.exports = {
  lintOnSave: false,
  //   devServer: {
  //     proxy: "https://apimusic.linweiqin.com/"
  //   }
  devServer: {
    proxy: {
      "/song": {
        target: "https://apimusic.linweiqin.com/",
        // changeOrigin: true,
      },
      "/api": {
        target: "http://s.linweiqin.com/",
      },
    },
  },
};

你可能感兴趣的:(vue,vue.js)