Static GitHub Issues

[2450] How to use nuxt in koa-router or express-router?

prev: nuxt ie9的兼容问题
next: How to define webpack on config.nuxt.js

I have some problems to use nuxt.js. I have a backend router hybrid, I want to use nuxt.render in this router, but I found 404 error in all assets, like '/_nuxt/app.xxxx.js', '_nuxt/layout.xxx.js'. Could you give any tips or a example which use koa-router.Thank you.

project structure

  • routes/hybrid/index.js
  • nuxt.config.js
  • .nuxt/
import Router from 'koa-router';
import { Nuxt, Builder } from 'nuxt';
const config = require('../../nuxt.config.js');
config.dev = !(process.env.NODE_ENV === 'production');
const nuxt = new Nuxt(config);
const hybrid = new Router();
hybrid.use('/', async (ctx, next) => {
  if (config.dev) {
    const builderIgnored = new Builder(nuxt);
    await new Builder(nuxt).build();
  }
  await next();
  ctx.status = 200; // koa defaults to 404 when it sees that status is unset
  return new Promise((resolve, reject) => {
    ctx.res.on('close', resolve);
    ctx.res.on('finish', resolve);
    nuxt.render(ctx.req, ctx.res, promise => {
      // nuxt.render passes a rejected promise into callback on error.
      promise.then(resolve).catch(reject);
    });
  });
});
export default hybrid;
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c2125">#c2125</a>)</em></sub></div>