Common asynchronous interface definitions in Nodejs (GET, post, JSONP)

Source: Internet
Author: User

More and more people are using Nodejs, as a service-side language, we inevitably write asynchronous interfaces (Ajax and JSONP). Again, Ajax and JSONP are two concepts, but because of jquery's encapsulation, the invocation of these two asynchronous interfaces looks similar, but the underlying difference is still relatively large (this article only writes the service-side implementation).

I use the express framework to run my demo for easy explanation. and explain how to get the parameters, and return the results. This article is equivalent to a basic article that only writes about some common application scenarios. Miss out on some complicated scenes and look for reminders.

First, Ajax--post request

I started with post because I wanted to get the get and jsonp closer. And the way to get the parameters of the post and two compared to the difference between the two is larger.

A basic POST request:

  1  var express = require (' Express '); var  router = Express. Router ();    3  router.post ('/simplepost ', function   (req, res, next) {  4  Span style= "color: #0000ff;" >var  param = Req.body;   //  Console.log (param);   //  Todo something   9  Res.json ({"ErrorCode": 0, "errormessage": ' Save ' });  11 }); 

Router is the object that defines the route in the framework, and we are equivalent to binding a callback function of the controller to the router. The callback function passes 3 variables, encapsulating the request (req), the response (RES), and the next middleware (next), respectively. In the post request, the parameters are encapsulated in req req.body we console.log (param); You can see the parameters in the console. With a series of operations, when we want to return the result (usually JSON), we need to invoke the JSON under RES to return an object to the client (front end).

Second, Ajax--get request

Get requests and post are roughly similar, but slightly different. Not much to say, first look at the code:

1 varExpress = require (' Express ');2 varRouter =Express. Router ();3 varUrllib = require (' URL ');4 5Router.get ('/simpleget ',function(req, res, next) {6     varparams = Urllib.parse (Req.url,true);7     //console.log (' params ', params);8     varquery =Params.query;9Todo SomethingTenRes.json ({"ErrorCode": 0, "errormessage": ' Save OK '}); One});

Get request parameters can not be removed directly in the req.body, to get the parameters will be loaded first load "url" module var urllib = require (' URL '); Through the module encapsulation method parse takes the object containing the parameter, and the query out, this is the print query, you can see the front-end parameters. As for the return result, the Clash post is the same.

Third, JSONP

Jsonp actually sends a JS file request, so it's essentially a GET request (but not Ajax). JSONP is the same as get (Ajax) in getting the parameters. But different in the way of returning results.

1 varExpress = require (' Express ');2 varRouter =Express. Router ();3 varUrllib = require (' URL ');4 5Router.get ('/simplejsonp ',function(req, res, next) {6     varparams = Urllib.parse (Req.url,true);7     varReqdata = {};8     varquery =Params.query;9     Ten      One     //res.send (reqdata); A     //Console.log (params); -  -         //Todo somthing the     if(Params.query &&params.query.callback) { -         varstr = params.query.callback + ' (' + json.stringify (reqdata) + ') ';//Jsonp - res.end (str); -}Else{ + res.end (Json.stringify (Reqdata)); -     } +});

We need to determine the property name "callback"--if (Params.query && params.query.callback) {} for the callback function that has a contract after obtaining the parameter. If not I think I can do the normal get (Ajax) to deal with, instead I think it is JSONP. Jsonp needs to return the result in a "call" way:

Params.query.callback + ' (' + json.stringify (reqdata) + ') ';

Summarize:

This completes the common asynchronous interface inventory, the article is some common most basic scenes. But this is also the cornerstone of complex scenarios. The wrong place in the text is also looking for a lot of treatise.

  

  

Common asynchronous interface definitions in Nodejs (GET, post, JSONP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.