nuxt nuxt.config.js 配置跨域问题

1/安装基本配置:

npm i axios qs
npm i @nuxtjs/axios @nuxtjs/proxy --save-dev

2/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);
  });
}

或者

import Qs from 'qs';
 
export default function (app) {
    let axios = app.$axios; 
    // 基本配置
    axios.defaults.timeout = 10000;
    axios.defaults.method = 'post';
    // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    axios.defaults.transformRequest = [function (data) {
        data = Qs.stringify(data)
        return data
    }],
    
    // 请求回调
    axios.onRequest(config => {})
    
    // 返回回调
    axios.onResponse(res => {})
    
    // 错误回调
    axios.onError(error => {})
}

3/配置nuxt.config.js


module.exports = {
  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '@/plugins/element-ui',
    { src: "~plugins/axios.js", ssr: true }
  ],
  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    //"@nuxtjs/proxy"
  ],
  /*
  ** Axios module configuration
  ** See https://axios.nuxtjs.org/options
  */
  axios: {
    //是否允许跨域
    proxy: true,
    //最多重发三次
    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://www.baidu.com',
      pathRewrite:{"^/api":''}
    }

  },
  /*
  ** Build configuration
  */
  build: {
    transpile: [/^element-ui/],
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
    }
  }
}

4/在页面使用this.$axios做请求

 this.$axios.post('/api/login',{
              mobile: 13211122233,
              pwd: 652545
   })
   .then((res) => {
      console.log(res)
   }).catch(()=>{
        console.log('eeee')
  })

参考方案:
https://www.jianshu.com/p/02475fd0fc3c
https://www.jianshu.com/p/003d9add4fd1
https://blog.csdn.net/weixin_36185028/article/details/82946681

你可能感兴趣的:(nuxt nuxt.config.js 配置跨域问题)