nuxt.js 跨域配置proxy代理


1. 安装axios: npm install --save axios

 

2. 安装 @nuxtjs/axios和@nuxtjs/proxy来处理 axios 跨域问题:  npm i @nuxtjs/axios @nuxtjs/proxy -D

 

3. nuxt.config.js中配置:

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,
    headers: { 'Content-Type': 'application/json', 'crossDomain': true },
    timeout: 5000,
  },
  proxy: {
    '/api/': {
      target: 'http://192.168.1.53:3009/',
      pathRewrite: {
        '^/api/': ''
      }
    }
  }
 
4. 使用: 
async login({ commit }, { username, Pwd }) {
        try {
            const { data } = await axios.post('/API/User/Login', { username, Pwd })
            console.log('apidata:', data)
            commit('SET_USER', data)
        } catch (error) {
            if (error.response && error.response.status === 401) {
                throw new Error('Bad credentials')
            }
            console.log(error)
            throw error
        }
    },


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM