nuxt-community / router-module

Nuxt 2 module to use router.js instead of pages/ directory.
MIT License
401 stars 28 forks source link

Use only in server side. #44

Closed lwswnnscrm closed 5 years ago

lwswnnscrm commented 5 years ago

Hi @Atinux , in my case i need take routes by ip user and host, but if i use context in createRouter function i get [nuxt] Error while mounting app: TypeError: Cannot read property 'req' of undefined. Can i use router only in server side?

Code:

import Vue from 'vue';
import Router from 'vue-router';
import generateRoutes from '~/helpers/generateRoutes';

Vue.use(Router);

export const createRouter = async (context) => {
  const host = context.req.headers.host;
  const ip = context.req.headers['x-forwarded-for'] || context.req.connection.remoteAddress;
  return new Router({
    mode: 'history',
    routes: await generateRoutes(host, ip),
  });
};
const generateRoutes = async (host, ip) => {
  const resultRouters = router;
  if (host.indexOf('exemple1.com') !== -1) {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page',
        component: page,
      },
    );
    return resultRouters;
  }
  if (host.indexOf('exemple2.com'') !== -1) {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page2',
        component: page2,
      },
    );
    return resultRouters;
  }
  if (host.indexOf('exemple3.com'') !== -1) {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page3',
        component: page3,
      },
    );
    return resultRouters;
  }
  const location = await generateRoutersByLocations(ip);
  if (location.toLowerCase() === 'au' || location.toLowerCase() === 'nz') {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page4',
        component: page4,
      },
    );
    return resultRouters;
  }
  resultRouters.unshift(
    {
      path: '/',
      name: 'mainPage',
      component: mainPage,
    },
  );
  return resultRouters;
};

export default generateRoutes;
const generateRoutersByLocations = async (ip) => {
  const { headers } = await axios.get(urls.apiUrl + urls.initPage, { params: { ip } });
  const location = headers['x-geo-ip-country'];
  return location;
};

export default generateRoutersByLocations;
This question is available on Nuxt community (#c36)
ghost commented 5 years ago

This issue as been imported as question since it does not respect router-module issue template. Only bug reports and feature requests stays open to reduce maintainers workload. If your issue is not a question, please mention the repo admin or moderator to change its type and it will be re-opened automatically. Your question is available at https://cmty.app/nuxt/router-module/issues/c36.

atinux commented 5 years ago

Hi @lwswnnscrm

To create routes for server-side only (like an API), I suggest you to take a look at the serverMiddleware.