This is the 22nd day of my participation in Gwen Challenge

NodeJS handles POST requests

Interface documentation

// URL  /tijiao carries data: {id: uniquely identifies numberusername: User name stringpassword: the password stringsex: Gender string male female secretage: Age number...... }// HTTP request mode
POST
// Return data
{  
   error: Error codedata: Detailed data...... }Copy the code

Get the data passed by POST

Because of the large amount of data submitted by POST requests. Maybe not all at once. NodeJS provides two events: Data and end. Used to help retrieve data.

demo:

// The data event is emitted every time data is passed
req.on("data".function(data_chunk) {
	console.log(1);
});
The end event is emitted when all data has been passed
req.on("end".function() {
	console.log("Data transfer completed")})Copy the code

Output:

The function argument data_chunk in the data event represents the data passed in this time.

Processing data received by POST (QueryStrings module)

Received data:

If we want to store this data, we must turn the string into an object.

NodeJS already provides the module queryStrings to handle such key: value pairs.

Usage:

var qs = require("querystring");
Copy the code

Processing:

req.on("end".function() {
	var obj = qs.parse(data);
	console.log(obj);
})
Copy the code

Results:

AJAX

Introduction to the

Asynchronous JavaScript and XML.

XML: Extensible markup language.

The front-end sends an asynchronous request through JS to get an XML data, which is secretly rendered to the page. XML has now been replaced by JSON in the front end. AJAX is not a new technology. In Internet Explorer 5, it already exists.

For example, XML:

<class name="style1" > 
    <name>Ajax learning</name>
    <students length=30>
      <student>
         <name></name>
         <age> </age>
         <sex></sex>
      </student>
       
    </students>
</class>
Copy the code

JSON:

{
   "name": "Ajax learning"."students": [{"name":,"age":,"sex"}}]Copy the code

Experience the AJAX

Netease Email Registration:

Petal net waterfall flow:

AJAX initialization

compatibility

Modern advanced browsers use AJAX objects that are instances of XMLHttpRequest.

Early Microsoft Internet Explorer browsers used instances of ActiveXObject(” microsoft.xmlhttp “).

demo:

/* Check whether the browser has the capability */
var xhr = null;
// Use the ActiveXObject constructor if there is one
if (window.ActiveXObject) {
	  xhr = new ActiveXObject("Microsoft.XMLHttp");
} else if (window.XMLHttpRequest) {
	  xhr = new XMLHttpRequest();
} else {
	console.log("Your browser does not support AJAX, please upgrade");
	return;
}
Copy the code

XHR object

Important attributes:

ReadyState: wait state code0: not initialized1The open method was called2: The response header has been received3: A portion of the returned content has been received4: After receiving all data, you can use itresponseText: Response textstatus: Indicates the status code of the HTTP request200Success:302: redirect304: the cache404: The resource was not found500: Server internal erroronreadystatechangeThe open method is used to open the request. The send method is used to send data. The setRequestHeader method is used to set the request headerCopy the code

The open method

Xhr. open(type, URL, Boolean) opens this link.type: Indicates the HTTP request mode. The get, post, etcurl: INDICATES the URL of the HTTP request. It could be a relative path or it could be an absolute pathboolean: Whether to send the message asynchronously or synchronously.trueFor asynchronous,falseFor synchronization.Copy the code

The send method

When xhr.send(data) is invoked, it indicates the sent text.

Data: data in the request body.

Three ways to convert a JSON string to an object

There are the following strings:

var str = {"error":1."data":"Already occupied"}
Copy the code

To object:

var result = JSON.parse(str);
Copy the code

Results obtained:

eval

The JSON object is added by ECMAScript5 and cannot be used in browsers that do not support ES5.

Eval is a string that is executed as code. It turns.

demo:

var str = '{"error":1,"data":" already occupied "}';
var result = eval("(" + str + ")")
Copy the code

Function

This is how constructors are used: the last argument is the body of the generated function, and the preceding arguments are all parameters of the generated function.

var result = new Function("return " + '{"error":1,"data":" already occupied "}') ();Copy the code

The path

Front-end absolute path

The slash (/) in the front-end absolute path indicates the root directory of the server

Back-end absolute path

The slash (/) in the back-end absolute path indicates the root directory of the disk

In the jQuery AJAX

Send a GET request

$.get(url, data, callback, type)
	url: URL stringdata: Carries data that can be a string or an object and can be omittedcallback: callback functiontype: The data type of the argument in the callback functionCopy the code
$.get("/checkName"."a=" + this.value, function(data) {
	tips.innerHTML = data.data;
}, "json")
Copy the code

Send a POST request

$.post(url, data, callback, type)
	url: URL stringdata: Carries data that can be a string or an object and can be omittedcallback: callback functiontype: The data type of the argument in the callback functionCopy the code
$.post("/checkName"."a=" + this.value, function(data) {
	tips.innerHTML = data.data;
}, "json")
Copy the code

$.ajax

The method used to send any request is a configuration object $.ajax(option)option: Configuration objecttype: HTTP request modedata: Carries data that can be a string or an object or omitteddataType: Indicates the type of data to be returnedsuccess: Callback function on successfailed: Callback function on failurecomplete: completes the callback functionCopy the code

Encapsulate your own AJAX sending functions

index.js:

var ickt = {
	get: function(url, data, callback) {
		// Define a string
		var str = "";
		if (typeof data === "string") {
			str = data;
		} else if (typeof data === "object") {
			for(var i in data) {
				str += i + "=" + data[i] + "&"}}var xhr = null;
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHttp");
		} else {
			console.log("AJAX not supported")
			return;
		}
		
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4) {
				callback(JSON.parse(xhr.responseText))
			}
		}
		xhr.open("get", url + "?" + str  , true);
		xhr.send();
	},
	post: function(url, data, callback) {
		// Initialize XHR
		var xhr = null;
                34// Ability test
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHttp");
		} else {
			return;
		}
		// Bind events
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4) {
				callback(JSON.parse(xhr.responseText)); }}Call the open method
		xhr.open("post", url, true);
		// Set the request header
		xhr.setRequestHeader("content-type"."application/x-www-form-urlencoded; charset=utf-8");
		// Call sendxhr.send(data); }}Copy the code

How to encapsulate a string of logical code?

A: Put this code in a function

How can data be both a string and an object?

A: Separate decision operations are performed inside the function

3 Why do I change the header of the Ajax request?

A: Because forms were early and Ajax was late, the server often built in the logic to process forms. But you can’t handle Ajax directly. So, as much as possible, disguise the data ajax sends as forms.