I want to send a html file and an object to the client from server using express such that when the file gets loaded it uses the object and structure dynamically using ajax.
I know that the html file can be send like this:
res.sendFile( __dirname + "/" + "main.html" )
object as:
res.json(obj);
But how to send them together?
I want to send a html file and an object to the client from server using express such that when the file gets loaded it uses the object and structure dynamically using ajax.
I know that the html file can be send like this:
res.sendFile( __dirname + "/" + "main.html" )
object as:
res.json(obj);
But how to send them together?
Share Improve this question asked May 29, 2018 at 9:52 sreepurnasreepurna 1,6762 gold badges21 silver badges33 bronze badges 3- This might not exactly answer your question, but it's good tool I used for the same purpose. Check it out: ejs. It's a templating engine for html that works with node.js Here is the npm module: npm – Stefan Octavian Commented May 29, 2018 at 9:56
- @StefanOctavian Thanks for the info. But this will not serve my purpose. – sreepurna Commented May 29, 2018 at 10:12
- See my answer and tell me if it helps you – Stefan Octavian Commented May 29, 2018 at 10:13
3 Answers
Reset to default 1In simple word, you can not send json and html together as we need to send content-type
in header. You can either send html or json.
Another way, you can send html into josn with other object something like following
const fs = require('fs');
const html = fs.readFileSync( __dirname + '/main.html' );
res.json({html: html.toString(), data: obj});
There are a couple of ways you can do that. While not the best method, this is the one I used in my projects. I used ejs, a powerful and simple templating engine.
First, install it using npm
npm install ejs
Then, in your HTML add:
<html>
<body>
<script type="text/javascript">
var obj = JSON.parse(<%= objSentFromServer %>)
// do something with obj
</script>
</body>
</html>
Server Side:
let express = require('express')
let app = express()
let ejs = require('ejs')
let fs = require('fs')
let objectSentFromServer = ... // what you need to send
app.get('/', (req, res) => {
fs.readFile(__dirname + '/main.html', (err, html) => {
res.send(ejs.render(html, JSON.stringify(objectSentFromServer)))
})
})
app.listen(8080, (err) => { console.log(err) })
Of course, there are plenty of other ways.
You may not be able to achieve this by sending back plain HTML. But you should be able to achieve this using a templating engine. With the help of templating engine, you should be able to render a view as well as pass JSON required to used in that template.
Reference: render view
Eg;
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
// ...
});
Here is the plete list of Template Engines supported by Express JS