简体   繁体   中英

node.js and handling multiple ajax calls with a sigle or multiple scripts

I just started diving in to Node.js the other day. I like what I have seen and it looks like what i need for my project.

I haven't found an answer to this and maybe i just don't know how to search for it correctly on the inter webs .

Will I be able to have a single Node.js script handle different ajax requests and response with different JSON based upon the request or will i need to have separate scripts listening on different ports to handle each different request.

I want to be able to pass in parameters to my ajax request to drive the script to execute a particular function and return JSON based upon those parameters.

As you are considering Node.js for your next project, you need a scale-able solution that can behave as a web server (accepting and responding to multiple requests on same port)

  • Yes you can have single script to handle multiple requests. However, since you want to respond to AJAX requests, you need a Webserver, not just a simple script.

Although you can convert Node.js into a simple HTTP Server by just using default http module. But for a real project you would need much more at the server end. eg accepting GET/POST requests, cookies, sessions, response types (JSON, HTML..), routing, redirection, authentication etc.

for that, there are already frameworks out there that will run on top of Node.js to transform it into a full blown WebServer. You can then tailor it to your needs, using their simple APIs.

My experience with one such framework ExpressJS , has been great so far. Easy to learn and extend.

  • Yes you can receive data in request and respond with HTML or JSON. In general, using one such http webserver framework, you will define Routes (eg '/users/:id) that will be invoked upon a request. At this point Framework will provide you with request and response objects to receive incoming data and generate response.

Express Examples in project repo are very helpful in exploring. Simply Download zip and go through the Readme file on repo.

Taken from the Node.js main page :

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Voila, one script handling many requests. Everything else is just a matter of proper parsing, processing and serializing data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM