简体   繁体   English

使用Node.js和Express将JSON数据与sendFile()一起发送的正确方法

[英]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. 我已经使用Express设置了Node.js服务器,并且已经设置了路由。 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. 导航到特定位置:“ / users / id”时,我当前正在使用sendFile(),但我也想将JSON数据传递到页面中。

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. 我知道我可以为页面提供服务,然后在页面加载时发出ajax请求,但是似乎我想尽可能减少服务器端调用。

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) (如果我不进行单独的ajax调用)

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)
      }
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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