res.sendfile in Node Express with passing data along

前端 未结 6 1650
失恋的感觉
失恋的感觉 2020-12-01 10:35

Is there any way to redirect to an HTML file from a Node.JS application with something like: res.sendFile of express and pass a JSON data along to the html file?

6条回答
  •  攒了一身酷
    2020-12-01 11:02

    You get one response from a given request. You can either combine multiple things into one response or require the client to make separate requests to get separate things.

    If what you're trying to do is to take an HTML file and modify it by inserting some JSON into it, then you can't use just res.sendFile() because that just reads a file from disk or cache and directly streams it as the response, offering no opportunity to modify it.

    The more common way of doing this is to use a template system that lets you insert things into an HTML file (usually replacing special tags with your own data). There are literally hundreds of template systems and many that support node.js. Common choices for node.js are Jade (Pug), Handlebars, Ember, Dust, EJS, Mustache.

    Or, if you really wanted to do so, you could read the HTML file into memory, use some sort of .replace() operation on it to insert your own data and then res.send() the resulting changed file.

提交回复
热议问题