Koa source code implementation
- The use of koa
const Koa = require("koa");
const app = new Koa();
app.use((ctx) => {
ctx.body = 'Hello World! '
})
app.listen(3000)
Copy the code
That’s how we use KOA. One of koA’s great inventions is CTX, which is koA’s context. CTX contains both REQ and RES. The above code is actually an HTTP service, the source code implementation is actually to consider in Node which module which method can be implemented on the port to achieve service listening.
- Handwritten koa
// index.js file const MyKoa = require("./lib/application");
const app = new MyKoa();
app.use((req, res) => {
res.end('Hello World! ')
})
app.listen(3000, () => {
console.log('Your application starts on port 3000');
});
Copy the code
Const HTTP = require(// application.js // lib // application.js // application.'http');
class MyKoa {
constructor() {
console.log('handwritten koa! 'This.fn = undefined; } / /... Args dynamic receiver parameter listen(... Args) {// Start server to pass in asynchronous callback functions to give user feedbackletserver = http.createServer(this.fn); server.listen(... args); } use(fn) {// Save this.fn = fn; } } module.exports = MyKoaCopy the code
Listen: app.listen and server.listen The first listen is the KOA API, and the second listen uses Node native code to implement the API.
XHR underlying implementation
- Please familiarize yourself with the format of HTTP packets before looking at the code.
// server.js
const http = require('http'); Http.createserver ((req, res) => {// Return the content res.end('OKOK! ');
})
.listen(8088, ()=> {
console.log(8088);
})
Copy the code
Const net = require(const net = require('net'); // Transport layer source port destination port // create a request // create a TCP connection to port and host (to initiate a request to the destination address) const client = net.createconnection ({port: 8088, host:'127.0.0.1'= > {}, ()letjson = JSON.stringify({a: 1}); // Concatenates packets line by line. Spaces cannot be omitted. //'/'// CR LF is the end of the line, with \r\n representing client.write('POST/HTTP / 1.1 \ r \ n');
client.write('the HOST: 127.0.0.1 \ r \ n');
client.write('Content-Type: application/json\r\n'); // Header and entity separator client.write('\r\n'); client.write(json); // Packet stitching ends Client.write ('\r\n'); }) // Data returned by the server client.on('data', (data) => {// Raw data as Buffer, convert it to string console.log('receive:', data.toString()); }) // Disconnect client.on('end', () => {
console.log('disconnect');
})
Copy the code
- “Modern times” sends out papers
const net = require('net');
class Xmlhttprequest {
constructor() {this.method = null; this.url = null; this.headers = null; this.body = null; This. resStatusLine = null; this.resHeaders = null; this.response = null; } open(method, url) {this.method = method; this.url = url; }setHeader(headers) { this.headers = headers; } // Parse (string) {const lines = string.split('\r\n');
console.log(lines);
this.resStatusLine = lines[0];
this.statusCode = this.resStatusLine.split(' ') [1]; this.resHeaders = lines.slice(1, lines.length - 2); this.response = lines[lines.length - 1]; } send(body) {this.body = body; // Establish a connection const client = net.createconnection ({port: 8088, host:'127.0.0.1'}, () => {// Splice the packet client.write('${this.method} ${this.url}HTTP / 1.1 \ r \ nHOST: 127.0.0.1 \ r \ nContent - Type: application/json \ r \ nContent - Length:${this.body.length}\r\n\r\n${this.body}\r\n ') // Send client.end(); }) // The data returned from the backend client.'data', (chunk) => {// The server also returns a original HTTP packet to the browser // parsing packet console.log('receive:', JSON.stringify(chunk.toString())); Parse parse the packet this.parse(chunk.tostring ()); // Call the special parse function parse the packet this.parse(chunk.tostring ()); // Call onload this.onload() after receiving data; }) client.on('end', () => {
console.log('disconnect');
})
}
}
// ajax
const xhr = new Xmlhttprequest();
xhr.open("POST"."/"); // define the request header xhr.setheader ({'Content-Type': 'application/json'}) // xhr.onload = is called only after the callback data is loadedfunction() {
//
console.log('Response data :'); Log (xhr.statuscode) console.log(xhr.response) // Get the response header console.log(xhr.resheaders)} // Xhr.send (json.stringify ({a: 1}))Copy the code
The above method of packet parsing is not the most general or “elegant” method, it is a relatively old method. But it helps a little bit to understand the underlying implementation.
conclusion
In front-end learning, we will encounter a variety of frameworks and apis. We can’t just stop at the stage where we know how to use it, but try to understand the underlying implementation as much as possible. After all, frameworks and apis are constantly being updated, and only by mastering the underlying fundamentals can change.