Express - Send a page AND custom data to the browser in a single request?

后端 未结 5 741
星月不相逢
星月不相逢 2020-12-23 23:05

How simultaneously to render a page and transmit my custom data to browser. As i understood it needs to send two layers: first with template and second with JSON data. I wan

5条回答
  •  时光说笑
    2020-12-23 23:14

    Most elegant and simple way of doing this is by using rendering engine (at least for that page of concern). For example use ejs engine

    node install ejs -s
    

    On server.js:

    let ejs = require('ejs');    
    app.set('view engine', 'ejs');
    

    then rename desired index.html page into index.ejs and move it to the /views directory. After that you may make API endpoit for that page (by using mysql module):

    app.get('/index/:id', function(req, res) { 
        db.query("SELECT * FROM products WHERE id = ?", [req.params.id], (error, results) => {
        if (error) throw error;
            res.render('index', { title: results[0] }); 
        });
    });  
    

    On the front-end you will need to make a GET request, for example with Axios or directly by clicking a link in template index.ejs page that is sending request:

    Click
    

    where co.id is Vue data parameter value 'co' that you want to send along with request

提交回复
热议问题