Res.Sendfile in Node Express With Passing Data Along

res.sendfile in Node Express with passing data along

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.

How to use BOTH res.sendFile(); and res.send(); in Node.js?

Solution

To get the parameters on client side, you need to use this function:

function searchToObject() {
var pairs = window.location.search.substring(1).split("&"),
obj = {},
pair,
i;

for ( i in pairs ) {
if ( pairs[i] === "" ) continue;

pair = pairs[i].split("=");
obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}

return obj;
}

var urlParameters = searchToObject();

If you don't need the url parameters from the server, you can do it this way.
urlParameters contains json object with url parameters.

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

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

send html file and data using express

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

Express post/send message to route

So I am answering my own question because I found out about js WebSockets, and the WebSocket-Node lib - they allow full-duplex communication beetween server, and client, and are simple to use. here is server code:

const nwss = require('websocket').server;
const http = require("http");

var server = http.createServer(function(request, response) {
console.log(' Received request for ' + request.url);
response.write("example")
response.end();
});

server.listen(8000, ()=>{console.log("ready")})

ws = new nwss({
httpServer: server,
autoAcceptConnections: false
})
ws.on('request', (req)=>{
let conn = req.accept('example-protocol', req.origin);
console.log('accepted ' + conn.remoteAddress)
conn.on('message', (msg)=>{
if (msg.type == 'utf8') {
console.log('Recieved utf8 ' + msg.utf8Data);
conn.sendUTF(`thanks for "${msg.utf8Data}"`)
}
})
conn.on('close', ()=>{
console.log(`${conn.remoteAddress} disconnected.`)
})
})

(it is a bad idea to allow other sites to connect, so use an if statement to check if the origin is ws://yoursiteurl/)
And client:

let socket_url = "ws://" + new URL(location.href).host + "/"
let WSocket = window['MozWebSocket'] ? MozWebSocket : WebSocket;
let socket_ = new WSocket(socket_url, 'example-protocol') //the example-protocol is the same i put in the server code, as it has to be.
function start() {
socket_.onmessage = (msg)=>{
console.log(msg.data)
}
socket_.send("hi, do you read? :P")
}
//call start once it connects.

Node Express Res SendFile

First of all it should produce error of
Headers can't be set once they are sent.

Becuse once the response from :
res.send('Pagina SendFile') is sent it won't send index.html file.

You should first set the view Engine like this :

app.set('view engine', 'html'); in your server.js file
And important of all you should keep all HTML files in views then set view engine & finally send using :

res.status(200).sendFile(__dirname + 'index.html')



Related Topics



Leave a reply



Submit