nuxt使用axios的跨域處理配置

騎著程式碼去流浪發表於2018-10-05
npm i axios qs
npm i @nuxtjs/axios @nuxtjs/proxy --save-dev

 

plugins/axios.js

使用qs將請求從引數轉化位字串

import qs from "qs";

export default function({ $axios, redirect }) {
  $axios.onRequest(config => {
    config.data = qs.stringify(config.data, {
      allowDots: true //Option allowDots can be used to enable dot notation
    });
    return config;
  });

  $axios.onResponse(response => {
    return Promise.resolve(response.data);
  });

  $axios.onError(error => {
    return Promise.reject(error);
  });
}

 

nuxt.config.js


  plugins: [
    { src: "~plugins/axios.js", ssr: true },
  ],
  //處理跨域問題
  modules: ["@nuxtjs/axios", "@nuxtjs/proxy"],
  axios: {
    retry: { retries: 3 },
    //開發模式下開啟debug
    debug: process.env._ENV == "production" ? false : true,
    //設定不同環境的請求地址
    baseURL:
      process.env._ENV == "production"
        ? "http://localhost:3000/api"
        : "http://localhost:3000/api",
    withCredentials: true,
  },
  proxy: {
    //開啟代理
    "/api/": {
      target: "http://192.168.1.2:10086/v1",
      pathRewrite: { "^/api/": "" }
    }
  }

 

在頁面使用使用this.$axios做請求

 

 

其他方案參考:

https://segmentfault.com/a/1190000010815403

https://segmentfault.com/a/1190000012550346

相關文章