Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass JS objects from the server-side to the clientside in NodeJS

In PHP I used to pass objects from the backend to the front end in JSON form, using script tags.

<script>

var serversideStuff = '<?php echo json_encode($serversideArray); ?>';

</script>

How can I pass JS objects from the server-side to the clientside using nodeJS, express and Jade. There is probably a really good way that I'm just not aware of.

Hope you can help me out.

like image 835
wilsonpage Avatar asked Oct 06 '11 17:10

wilsonpage


People also ask

How do you pass an object in node js?

How to pass an object to another function in Node. js. Here's a working example of that function passing technique: var http = require('http'); function OnRequest(request, response) { sendPage(request, response); //This is where the request and response objects are passed as parameters. }

Is node js server-side or client-side?

Node. js is a server-side JavaScript run-time environment. It's open-source, including Google's V8 engine, libuv for cross-platform compatibility, and a core library.

How do I connect to a client server in node js?

Socket(); client. connect(PORT, HOST, () => { console. log(`client connected to ${HOST}:${PORT}`); // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client client.


1 Answers

In PHP you use bad practices (dynamically generating javascript as part of an application).

With node you do it right. This means you

  • Either write the data to the HTML (How would your website work without javascript, you are using progressive enhancement, right?)
  • Expose that data as a web service you talk to over Ajax or WebSockets
like image 199
Raynos Avatar answered Sep 22 '22 14:09

Raynos