This is the ninth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

When a user sends a data request, the common methods are GET and POST requests. Whether the user sends GET or POST, the data is in the request content object

  1. To obtainGETData in three ways

Get data is sent in request.url. Request represents the content object of the request, which contains a lot of information related to the request.

Method 1: Manually cut

The request data in the URL string is cut into JSON format using the split method in the string

const http=require("http");// Import the HTTP module
http.createServer(function(req,res){// Create the server through the HTTP module object
	//req gets the data sent by the foreground
	var GET ={};
	if (req.url.indexOf('? ')! = -1) {
		var arr = req.url.split('? ');
		var url=arr[0];/ / address
		var arr2 = arr[1].split('&');
		for (var i = 0; i < arr2.length; i++) {
			var arr3 = arr2[i].split('=');
			GET[arr3[0]]=arr3[1]; }}else{
		var url=req.url;
		// GET={}
	}
console.log(url,GET);
res.write("aaa");// Respond to what is written on the page
res.end();// End the response
}).listen(8080);// Ask for a port and listen
Copy the code

Method two: Use the QueryString module

Querystring, like HTTP, is a built-in module of node. You can use the parse method of querystring to convert a querystring into json

const http = require('http');
const querystring=require('querystring');
http.createServer(function(req,res){
	var GET={};
	if (req.url.indexOf('? ')! = -1) {
		var arr=req.url.split('? ');
		var url = arr[0];
		GET=querystring.parse(arr[1]);//
	}else{
		var url=req.url;
	}
	console.log(GET);
	res.write('aaaa');
	res.end();
}).listen(8080);
Copy the code

Method three: Use the URL module

The URL is also a module provided by Node. Parse the entire URL into an object using the parse method in the URL module. The query attribute corresponds to the GET data we want, and the second parameter true will be automatically parsed into JSON

const http = require('http');
const urlLib = require('url');
var GET={};
http.createServer(function(req,res){
	var obj=urlLib.parse(req.url,true);
	var url=obj.pathname;
	var GET=obj.query;

	console.log(url,GET);
	res.write('aaaaa');
	res.end();
}).listen(8080);
Copy the code

There are three ways to obtain data from a GET request. The third is recommended

  1. To obtainPOSTRequested data

Compared with GET data, POST data is large in volume and has segments. Req.on (‘data’,function(data){}) listens, and executes a callback when a segment of data arrives. The callback argument is data for each segment. The callback function in req.on(‘end’,function(){}) is fired when all the data has arrived. Querystring.parse (STR) can be parsed into the POST request data format we want

var http=require('http');
var querystring=require('querystring');
http.createServer(function(req,res){	
	var str=' ';
	var i=0;
	req.on('data'.function(data){
		console.log(The first `${++i}Received data ');
		str+=data;
	});// When a piece of data has arrived
	req.on('end'.function(){
		var POST=querystring.parse(str);
		console.log(POST);
	});// All data arrived
}).listen(8080);

Copy the code
  1. Reading and writing files

Files are read through the fs module. There is a readFile(file to read, callback function) to read the file. When the file is read, the callback is executed

For three kinds of requests: file request or GET request or POST request, let’s build a complete server prototype

// Introduce the corresponding module
const http=require('http');// HTTP protocol related
const fs=require('fs');// File system related
const querystring=require('querystring');// Query string correlation
const urlLib=require('url');// Handle URL related

var server=http.createServer(function(req,res){
	//GET
	var obj=urlLib.parse(req.url,true);
	var url=obj.pathname;
	const GET=obj.query;

	//POST
	var str=' ';
	var POST=' ';
	req.on('data'.function(data){
		str+=data;
	});
	req.on('end'.function(){
		POST=querystring.parse(str);
	});
	// console.log(url,GET,POST)

	// File request
	var file_name='./www'+url;
	fs.readFile(file_name,function(err,data){
		if (err) {
			res.write("404");
		}else{
			res.write(data);
		}
		res.end();
	});

});

server.listen(8080);// Ask for a port and listen for it
Copy the code

So that’s how Nodejs gets GET and POST data and how it reads the requested file and responds