Nuxt如何发起跨域资源请求?

用于 Nuxt.js 的 http-proxy 中间件解决方案

npm i @nuxtjs/proxy -D

在 nuxt.config.js 配置文件中添加对应的模块,并设置代理

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  axios: {
    
    
    proxy: true
  },
  proxy: {
    
    
    '/api': {
    
    
      target: 'http://example.com',
      pathRewrite: {
    
    
        '^/api' : '/'
      }
    }
  }

实战

nuxt.config.js

modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    // https://go.nuxtjs.dev/pwa
    '@nuxtjs/pwa',
    // https://go.nuxtjs.dev/content
    '@nuxt/content',
    // 跨域
    '@nuxtjs/proxy'
  ],

  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {
    
    
    proxy: true,
    common: {
    
    
      'Accept': 'application/json, text/plain, */*'
    },
  },
  // 跨域
  proxy: {
    
    
    '/api': {
    
    
      target: 'http://127.0.0.1:3001',
      pathRewrite: {
    
    
        '^/api' : '/'
      }
    }
  },

mock.js

const Mock = require('mockjs')

let Result = {
    
    
	code: 200,
	msg: "操作成功",
	data: null

}

// 获取人物信息
Mock.mock('/api/user', 'get', () => {
    
    
	Result.data = {
    
     "userInfo": {
    
     "id": 9979, "userName": "Redmi K30", "productImg": "public/imgs/phone/Redmi-k30.png", "price": 1599, "num": 1, "maxNum": 5, "check": false } }
	Result.msg = "购物车错误"
	return Result
})

业务

created() {
    
    
    this.getUserInfo();
  },
  methods: {
    
    
    getUserInfo() {
    
    
      console.log("已经进入了++++++++");
      this.$axios
        .get("/api/user")
        .then((res) => {
    
    
          this.user = res.data.userInfo;
          console.log(JSON.stringify(res.data.data) + "=====res.data.data");
        })
        .catch((err) => {
    
    
          return Promise.reject(err);
        });
    },
  },

截图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43874301/article/details/119257097

相关文章