1

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?

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 Commented May 29, 2018 at 9:56
  • @StefanOctavian Thanks for the info. But this will not serve my purpose. Commented May 29, 2018 at 10:12
  • See my answer and tell me if it helps you Commented May 29, 2018 at 10:13

3 Answers 3

1

In 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});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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 complete list of Template Engines supported by Express JS

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.