0

I want to invoke function init() { // } present in app.js from html page from

<a href='javascript:init();'> invoke init </a>

The problem with the above code is, that it looks for function init() only at the client side, whereas I want to invoke function init() at the express server app.js.

1 Answer 1

2

Despite using the same language, client and server have no direct ties to each other. They're still bound to communicating with HTTP or WebSockets.

So, you'll need to establish a route that will call init() when requested:

app.get('/init', function (req, res) {
    init();
    // res.send(...), etc.
});

Then have the client either navigate to it:

<a href="/init"> invoke init </a>

Or, request it via Ajax:

function init() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/init');
    xhr.send();
}
Sign up to request clarification or add additional context in comments.

4 Comments

How can i do it using websockets?
@Swagg Node.js doesn't pre-define support for the WebSocket protocol like it does with HTTP, so you'll need to find a library/framework that implements it on top of the net module. Probably the most common is Socket.IO, but there are certainly others.
can something like angularjs be used for it?
@Swagg I don't believe Angular defines any modules for WebSockets, specifically. But, it can be used along with Socket.IO or the native WebSocket class.

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.