Saturday 18 March 2017

Set current request route in vue-router for SRR in server-side with Node.js

Introduction

I have this Node.js code from a function that handle the request/response. To explain my problem, I will use Express.js example. That piece of code is not a part of my problem but I can include to you a simple context to help you answer my question. So my code will be put in app.get handler, assuming app is an Express.js instance :

app.get("/", function (request, response, next) {
    // The code below could be here...
});
app.get("/test/", function (request, response, next) {
    // ...and here...
});
app.get("/*", function (request, response, next) {
    // ...and here...
});

  • response is the representation of response I will send to the client and I will fill it with the Vue Renderer result.

  • request contains all information about the client that execute this part of code.

My code

Assuming my code is running from the / route, the code is for example the following :

app.get("/", function (request, response, next) {
    var Vue = require("vue"),
        VueRouter = require("vue-router"),
        renderers = require("vue-server-renderer"),
        renderer = renderers.createRenderer();

    global.Vue = Vue;
    Vue.use(VueRouter);

    stream = renderer.renderToStream(new Vue({
        template: "<div><router-view></router-view><div>",
        router: new VueRouter({
            mode: 'abstract',
            routes: [{
                path: '/', 
                component: { template: '<div>foo</div>' }
            }, { 
                path: '/test/', 
                component: { template: '<div>bar</div>' }
            }, { 
                path: '/*', 
                component: { template: '<div>baz</div>' }
            }]
        })
    }));

    response.write("<html><head><title>test</title></head><body>");

    stream.on('data', function (chunk) {
        response.write(chunk);
    });

    stream.on('end', function () {
        response.end('</body></html>');
    });
});

And when response.end is called, the content send to the client is

<html><head><title>test</title></head><body><div server-rendered="true"><!----></div></body></html>

We can see the part where the router should be display the component is <!----> so I guess it's because for router, no route actually match my code.

Questions

Why the result is not the following if no route matchs :

<html><head><title>test</title></head><body><div server-rendered="true"><div>baz</div></div></body></html>

and

How to inform my router the current url is / to generate this code in this case :

<html><head><title>test</title></head><body><div server-rendered="true"><div>foo</div></div></body></html>

and for exemple the following code if my current request come from /test/

<html><head><title>test</title></head><body><div server-rendered="true"><div>bar</div></div></body></html>

etc.



via Haeresis

No comments:

Post a Comment