The HTTP module is the core module of NodeJS. It is easy to use, just create a server, listen to the port, and the whole service runs
let http = require('http');
let server = http.createServer(function(req,res){
});
server.listen(8080);
Copy the code
In callback of HTTP module createServer, REQ (Request) represents client data and is a readable stream. Res (Response) represents data on the server and is a writable stream. You can get the data you want:
let http = require('http');
let server = http.createServer();
server.on('request'.function (req, res) {
let buffers = [];
req.on('data'.function (data) {
buffers.push(data);
});
req.on('end'.function () {
console.log(Buffer.concat(buffers).toString());
res.write('hello node');
res.end();
});
});
Copy the code
A request event is an event that listens for a request. Buffers are used to receive buffer data from the server and console out at end. Res. write is a write event for a writable stream that writes data to the client. Of course, we can’t print the buffer here because there’s still one request header missing. Next, we’ll use code to simulate how the HTTP module works so that you can see it at a first view.
The server code is the same as the previous code, except that we will use the request header to determine the format of the data we receive from the client
let http = require('http');
let queryString = require('querystring');
let server = http.createServer();
server.on('request'.function (req, res) {
let contentType = req.headers['content-type'];
let buffers = [];
req.on('data'.function (chunk) {
buffers.push(chunk);
});
req.on('end'.function () {
let content = Buffer.concat(buffers).toString()
if(contentType === 'application/json'){
console.log(JSON.parse(content).name)
}else if(contentType === 'application/x-www-form-urlencoded'){
console.log(queryString.parse(content).name)
}
res.end('hello node');
});
});
server.listen(8080);
Copy the code
On the client side we organize all the header information of the request into a JSON and get the client data with the response event
let http = require('http');
let options = {
hostname: 'localhost',
port: 8080,
path: '/',
method: 'get'// Tell the server what type of data I want to send you'Content-Type': 'application/json', / /'Content-Length'}, headers:{// Form data format'Content-Type':'application/x-www-form-urlencoded'.'Content-Length': 16,,}}let req = http.request(options);
req.on('response'.function(res){
res.on('data'.function(chunk){
console.log(chunk.toString());
});
});
// req.end('{"name":"haha"}'); // json data format req.end('name=haha&age=18'); // Form data formatCopy the code
Then run the server file and use CMD to switch to the directory where the file resides and run the client file
Nodehttpclient.js // The name of the client fileCopy the code
The server type {name: ‘haha’, age: ’18’} and the client type Hello Node