简体   繁体   中英

Proper way to send JSON data along with sendFile() with Node.js and Express

I've setup a Node.js server with express and I've setup routing. When navigating to a specific location: "/users/id", I'm currently using sendFile(), but I'd also like to pass JSON data into the page.

I know I can serve the page and then make an ajax request on page load, but it seems like I would want to minimize server side calls as much as possible.

I would like to do something like below, but even if this works I'm not sure how to grab the data from the web page side. (If I'm not making a separate ajax call)

app.get('/'+element+'/:id', (request, response) => {
            const id = request.params.id;
            pool.query('SELECT * FROM '+element+' WHERE id = ?', id,(error, result)=>{
            if(error) throw error;
            response.sendFile(path.resolve(__dirname+'/../html/index.html'));
            response.json({message: result.name});
            });
        });

I'd like to return the data and the file and I'd like to know how to grab the data if I send it at the same time as the file.

Since you only need to to accommodate a simple string for the example you've given, you might consider accomplishing this through a response header. While it's not the most conventional approach, it might be the easiest in your case.

app.get('/' + element + '/:id', function(request, response, next) {
  let id = request.params.id;
  pool.query('SELECT * FROM ' + element + ' WHERE id = ?', id, (error, result) => {
    if (error) throw error;
    let options = {
      dotfiles: 'deny',
      headers: {
        'x-timestamp': Date.now(),
        'x-sent': true,
        'x-result-message': result.name // your custom header here
      }
    }
    let fileName = path.resolve(__dirname + '/../html/index.html')
    response.sendFile(fileName, options, function(err) {
      if (err) {
        next(err)
      } else {
        console.log('Sent:', fileName)
      }
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM