admin管理员组文章数量:1391975
I'm working on creating a basic login system, and since the server-side uses NodeJS, but client-side doesn't. I have to make any calls that use NPM packages on the server side. The issue is I have no clue how to call a server-side NodeJS function from the Client-Side JavaScript. Basically I wan't to be able to call a function that's stored on the server from the client browser.
I'm working on creating a basic login system, and since the server-side uses NodeJS, but client-side doesn't. I have to make any calls that use NPM packages on the server side. The issue is I have no clue how to call a server-side NodeJS function from the Client-Side JavaScript. Basically I wan't to be able to call a function that's stored on the server from the client browser.
Share Improve this question asked Dec 22, 2018 at 16:09 Ethan MitchellEthan Mitchell 6025 silver badges15 bronze badges4 Answers
Reset to default 4Make a route in your nodejs application like so:
app.get('/users', function(req, res) {
// Your function to be called goes here.
});
Now you can call this code from your client side javascript using ajax. Like this:
$.ajax({
type: 'GET'
url: 'http://localhost:8000/users',
success: function(response) {
console.log(response);
},
error: function(xhr, status, err) {
console.log(xhr.responseText);
}
});
Create a REST API and map the request parameters to the specific function calls you need to use. See this tutorial on creating REST APIs.
You do this by calling APIs on the server (a specific url that will to some specific work).In JS you need ajax. Have a look here
//url be the api like '/api/something/'
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
// your response
}});
});
in Node we have axios that will do the same example
axios.post('api/tobackend/function',{user:'a',password:'b'})
.then((res)=>console.log('response from server'))
in backed you might need route to handle the request.
router.post('api/tobackend/function',(reqs,resp)=>{console.log('backend')})
With Socket.io
in JS
let xhr = new XMLHttpRequest(); xhr.open('GET', '/user/sessionDestroy'); xhr.send();
In Node.JS
本文标签: nodejsHow to call a serverside NodeJS function using clientside JavaScriptStack Overflow
版权声明:本文标题:node.js - How to call a server-side NodeJS function using client-side JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744694471a2620193.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论