Use Express.js in an existing Nuxt.js project

落爺英雄遲暮 提交于 2019-12-11 15:06:06

问题


I have a project built with Nuxt.js and I want to use express to be able to report bugsnag errors on my asyncData method etc.

How would I go to import that? I suppose is not as simple as npm install express --save.

I already have an api written in PHP so I would not use that as an api or anything else.

Is it overkill? Or is it a necessary evil? :D


回答1:


You dont need express to handle errors in asyncData. To handle errors in asyncData/fetch on ssr you just need to hook into render:errorMiddleware. See sentry plugin for nuxt for example

But it would only catch errors that happens on SSR. On client unfortunately that wont catch anything ( as well as express wont do anything for client). There is a bug for this in nuxt see here




回答2:


To start using Express with an existing Nuxt project, you'll need to set up a simple server.js file that sets up your Express server and adds your Nuxt application as middleware. The only slight complication is setting it up to auto-rebuild in development. Here's a quick example server.js file that pulls in Nuxt and handles building when not in production.

const { Nuxt, Builder } = require('nuxt');
const app = require('express')();


// We instantiate Nuxt.js with the options
const isProd = process.env.NODE_ENV === 'production';
const config = require('./nuxt.config.js');

config.dev = !(isProd);
const nuxt = new Nuxt(config);

// No build in production
if (!isProd) {
  const builder = new Builder(nuxt);
  builder.build();
}
app.use(nuxt.render);
app.listen(3000);
console.log('Server is listening on http://localhost:3000');

You can then incorporate bugsnag as you normally would in express, I assume by requiring it and including it as middleware.



来源:https://stackoverflow.com/questions/51028514/use-express-js-in-an-existing-nuxt-js-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!