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

后端 未结 5 748
星月不相逢
星月不相逢 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:18

    My approach is to send a cookie with the information, and then use it from the client.

    server.js

    const visitCard = {
      name: 'John Smit',
      phone: '+78503569987'
    };
    
    router.get('/route', (req, res) => {
      res.cookie('data', JSON.stringify(pollsObj));
      res.render('index');
    });
    

    client.js

    const getCookie = (name) => {
      const value = "; " + document.cookie;
      const parts = value.split("; " + name + "=");
      if (parts.length === 2) return parts.pop().split(";").shift();
    };
    
    const deleteCookie = (name) => {
      document.cookie = name + '=; max-age=0;';
    };
    
    const parseObjectFromCookie = (cookie) => {
      const decodedCookie = decodeURIComponent(cookie);
      return JSON.parse(decodedCookie);
    };
    
    window.onload = () => {
      let dataCookie = getCookie('data');
      deleteCookie('data');
    
      if (dataCookie) {
        const data = parseObjectFromCookie(dataCookie);
        // work with data. `data` is equal to `visitCard` from the server
    
      } else {
        // handle data not found
      }
    


    Walkthrough

    From the server, you send the cookie before rendering the page, so the cookie is available when the page is loaded.

    Then, from the client, you get the cookie with the solution I found here and delete it. The content of the cookie is stored in our constant. If the cookie exists, you parse it as an object and use it. Note that inside the parseObjectFromCookie you first have to decode the content, and then parse the JSON to an object.

    Notes:

    • If you're getting the data asynchronously, be careful to send the cookie before rendering. Otherwise, you will get an error because the res.render() ends the response. If the data fetching takes too long, you may use another solution that doesn't hold the rendering that long. An alternative could be to open a socket from the client and send the information that you were holding in the server. See here for that approach.

    • Probably data is not the best name for a cookie, as you could overwrite something. Use something more meaningful to your purpose.

    • I didn't find this solution anywhere else. I don't know if using cookies is not recommended for some reason I'm not aware of. I just thought it could work and checked it did, but I haven't used this in production.

提交回复
热议问题