node. JS background Advanced (i)

Source: Internet
Author: User
Tags server memory

Backstage for our front-end may be really a little strange, let me clarify my thoughts.

A basic background requirement has the following functions:

1. Interacting with the front-end data

2. Operational database (add and revise)

3. Operation Server files (also probably adding and deleting)

Let's talk about the data interaction of the front and back end first.

To achieve data interaction, we have to write the interface , the interface is usually divided into 3 categories: GET, Post (Enctype=urlencode), post (Enctype=multipart/form-data)

The main problem with writing interfaces is the pathname and parameters of the request.

For example: Http://www.test.com/hahaha/test?name=rick, where "/hahaha/test" is pathname, the parameter is Name=rick

First, GET

This is obviously the method we use to enter the domain name to access the page, of course, we can also use form submission ,Ajax and Jsonp to implement.

Get compared to post requests is simpler because we don't have to consider the body of the request when we get the request, everything we need is only available in headers.

Get parameters can only be attached to the URL, directly on the code bar:

Const HTTP = require (' http '= require (' url '= Http.createserver (req,res) + ={  = Url.parse (Req.url,true);   // This is the API name  we want. // here is the parameter JSON we want }) Server.listen (8080);

Second, the POST value format is application/x-www-form-urlencoded

The so-called urlencoded format is a parameter format that is shaped like "a=123&b=abc"

And get different is in addition to the URL can take parameters, but also in the request body with parameters, but this format is generally not to pass the file, if put a <input type= "file" name= "F1"/> in the form, When submitting the browser will only bring up, file filename (shape like f1=1.txt)

Const HTTP = require (' http '); Const URL= require (' URL '); Const querysting= Require (' querystring '); Const server= Http.createserver ((req,res) ={  //get Parameters on pathname and URLs like getlet {pathname,query} = Url.parse (Req.url,true); Let PostData= [],poststr= ""; Req.on (' Data ',data=>{    //first of all the data stream memory, in fact, this is not good, will soon cause server memory is not enoughPostdata.push (data); }) Req.on (' End ', () ={    //data streams are connected togetherLet Postbuffer =Buffer.concat (postdata); //if the content-type inside the headers is application/x-www-form-urlencoded opening,    if(req.headers[' Content-type '].startswith (' application/x-www-form-urlencoded ')) ) {Poststr=postbuffer.tostring (); Console.log (Querysting.parse (POSTSTR)); //JSON parameters from the body}) }) Server.listen (8088);

Third, the POST value format is Multipart/form-data

The format of the data is very strange, but we pass the file is the test of the format to pass

This data is probably long:

The above data is the result of buffer to string, it is disgusting ~ ~ below, we are going to use this data processing as we can

Node has a buffer object, but buffer does not have a built-in Split method, so add the split method to buffer first

function (spliter) {  this;   = [];  Let index=0;    while ((Index=_this.indexof (spliter))!=-1) {let    res1= _this.slice (0, index);     = _this.slice (index+spliter.length);    Res.push (res1);     = res2;  }  Res.push (_this);   return Res;}

As for the delimiter in the boundary of headers[' Content-type ']

Then after a more complicated operation, we get the parameters we want:

functionParsepostjson (arr) {Let result= [],temparry = []; Arr.foreach (Item={Let temp= Item.slice (2,item.length-2); Let Index= Item.indexof (' \r\n\r\n '); Let Temp2= Temp.slice (0, index); Let Data= Temp.slice (index+2); Temparry= Temp2.split ('; ‘); Let name= Temparry[1].split (' name=\ ') [1].split (' \ "\ r \ n ') [0].tostring (). replace (' \" ', ')); Let Tempobj={name,data, filename: (temparry[2]?temparry[2].split (' filename=\ ') [1].split (' \ \ \ r \ n ') [0]: '). toString ()};  Result.push (Tempobj); })  returnresult;} Let Boundary= req.headers[' Content-type '].split ('; ') [1].split (' boundary= ') [1];let Temp= Postbuffer.split ('---' +boundary); Temp.pop (); Temp.shift (); let result=Common.parsepostjson (temp); Console.log (result);//This gets the parameters we want.

The result after processing is about the length of this

Then there is filename in accordance with the method of the file, for example WriteFile (filepath,data,err=>{}), filename is empty description is the normal string data, directly tostring () just fine

node. JS background Advanced (i)

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.