[Vuejs]-How to render a Nuxt page as a response from an express route

0👍

I’m not an expert on Nuxt so I can’t help you with certain details, but I can tell you that if you start off with a default nuxt-express project, you can edit server/index.js to include something like the following:

function doThePromise( query ) {
        return new Promise( ( resolve, reject ) => {
                setTimeout( () => resolve( "hi" ), 500 );
        } );
};

app.get( '/foo', ( req, res, next ) => {
        doThePromise( req.query )
                .then( data => {
                        console.log( "rendering", res.renderRoute );
                        res.renderRoute( 'pages/foo', { data: data } );
                } );
} );

If you then create a vue document at pages/foo.vue and access /foo in your browser, the promise will resolve after 500ms and perform the callback which renders the route and displays the desired page.

This solution seems to work but does not address two things:

  • The argument for renderRoute is actually supposed to be a context object containing req and res properties, according to the documentation. I don’t know how you’re actually supposed to forward data in the response, but this doesn’t seem to be the appropriate way.
  • I’m not even certain that renderRoute should be used in this way. In the documentation it’s used within the resoultion of a Nuxt Builder object, which I suspect might be intended to be a one-time operation rather than something that you would call repeatedly each time a request is made. I’m not sure either way, but it would probably be best to check. It might pay to look over the nuxt-express page for some examples of how to render routes and pass data in the rendering process.

Good luck!

Leave a comment