Nuxt.js与Egg.js通信及跨域等问题解决方案

Nuxt.js与Egg.js通信及跨域等问题解决方案

错误写法展示

错误1

nuxt   test.vue

async asyncData ({
      params }) {
     
    const {
      data } = await axios.get(`http://127.0.0.1:7001`);
    console.log(data);
    return {
      navItems: data }
  },

egg   main.js

class HomeController extends Controller {
     
  async index() {
     
    var navItems = [{
     
        name: "Home",
        indexPath: "/home",
        index: "1"
      },
      {
     
        name: "About",
        indexPath: "/about",
        index: "2"
      },
      {
     
        name: "More",
        indexPath: "/more",
        index: "3"
      }
    ];
    const {
     
      ctx
    } = this;
    ctx.body = navItems;
  }
}

问题描述:会产生跨域问题,前端点击链接并不会跳转并报错,但是浏览器的url会改变,这时直接刷新可以正常显示,并且test.vue第三行可正常解析打印。
Access to XMLHttpRequest at ‘http://127.0.0.1:7001/’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Error: Network Error
ReferenceError: NuxtError is not defined
Uncaught (in promise) Error: Network Error
Nuxt.js与Egg.js通信及跨域等问题解决方案_第1张图片

错误2

为解决上述跨域问题,前端Nuxt.js中采用如下写法

nuxt   test.vue

  async asyncData ({
      params }) {
     
    const {
      data } = await axios.get(`/api`);
    console.log('xixixi');
    console.log(data);
    return {
      navItems: data }
  },

nuxt   nuxt.config.js

  axios: {
     
    proxy: true,
    prefix: '/api',
    credentials: true
  },
  proxy: {
     
    '/api': {
     
      target: 'http://127.0.0.1:7001',
      changeOrigin: true,
      pathRewrite: {
     
        '^/api': '/',
      }
    }
  },

这时在前端点击链接可正常跳转到test.vue页面并显示数据,test.vue第三行也可正常打印输出,但是如果在跳转后的页面点击浏览器的刷新按钮会报错:
ERROR connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16)
Nuxt.js与Egg.js通信及跨域等问题解决方案_第2张图片
分析查找后觉得应该是应为async asyncData机制的原因


解决方案

修改package.json,添加如下配置

  "config": {
     
    "nuxt": {
     
      "host": "0.0.0.0",
      "port": "80"
    }
  }

注意修改完后要重启服务器,并且重启后要访问80端口
这样也带来了一个问题:多端口映射该如何配置?下一步将分析解决

你可能感兴趣的:(门户网站及CMS,nuxt.js,egg.js,跨域,async,asyncData,asyncData)