Node.js study notes - http module

There is a built-in module called http, we can use this module rapid development in Node.js in an http service.

First, the most basic version

index.js

const http = require('http');

const server = http.createServer();

server.on('request', (request, response) => {
  response.statusCode = 200;
  response.end('hello Node.js');
});

server.listen(3000);
复制代码

Start the service in the terminal node index.js

By postman request http://localhost:3000, or directly in the browser address bar http://localhost:3000, you'll see hello Node.js these lines.

II. Different url path back different content

const http = require('http');

const server = http.createServer();

server.on('request', (request, response) => {
  const { url } = request;
  console.log(url);
  response.statusCode = 200;
  switch (url) {
    case '/hello':
      response.end('Hello, meet again.');
      break;
    case '/bye':
      response.end('Talk to you next time');
      break;
    default:
      response.end("I don't know what you say.");
      break;
  }
});

server.listen(3000);
复制代码

effect:

By request of the url, you can return different content depending on different paths, pay attention to request.url will match everything after the domain name.

III. Get request processing parameter

const http = require('http');
const urlParse = require('url');
const qs = require('querystring');

const server = http.createServer();

server.on('request', (request, response) => {
  const { url } = request;
  const { query, pathname } = urlParse.parse(url);
  const { amount } = qs.parse(query);
  response.statusCode = 200;

  switch (pathname) {
    case '/borrowMoney':
      if (Number(amount) > 500) {
        response.end('go away');
      } else {
        response.end('here you are');
      }
      break;
    case '/bye':
      response.end('Talk to you next time');
      break;
    default:
      response.end("I don't know what you say.");
      break;
  }
});

server.listen(3000);

复制代码

Url by this module, the request url can be decomposed into such an object:

Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?amount=100',
  query: 'amount=100',
  pathname: '/borrowMoney',
  path: '/borrowMoney?amount=100',
  href: '/borrowMoney?amount=100'
}
复制代码

Url then the object by the decomposition of the query querystring then =divided so that it can handle a get request parameter band.

IV. The method of processing different requests

HTTP requests There are many ways, there are common: GET, POST, PUT, DELETE, OPTIONS, PATCH, etc., in the interface design in restful style, would be a url with, judged by different methods of what you need to do this request, such as:

http://localhost:3000/user
复制代码

Only such an interface, the POST request a new user, GET requests to read a user, PATCH user requests an update, DELETE request to delete a user.

RESTful API Best Practices

To achieve RESTful style interface, the server will request the determination method.

const http = require('http');
const urlParse = require('url');
const qs = require('querystring');

const server = http.createServer();
let users = [];
let userId = 0;

function updateUsers(res, method, id) {
  switch (method) {
    case 'GET':
      res.end(JSON.stringify(users));
      break;
    case 'POST':
      userId += 1;
      const user = { id: userId };
      users.push(user);
      res.end(JSON.stringify(user));
      break;
    default:
      res.statusCode = 405;
      res.end('Method Not Allowed');
      break;
  }
  users = users.filter(item => item.id !== id);
  res.end(JSON.stringify(users));
}
server.on('request', (request, response) => {
  const { url, method } = request;
  const { pathname, query } = urlParse.parse(url);
  const { id } = qs.parse(query);
  response.statusCode = 200;
  switch (pathname) {
    case '/user':
      updateUsers(response, method, id);
      break;
    default:
      response.end("I don't know what you say.");
      break;
  }
});

server.listen(3000);

复制代码

The method of obtaining the request by the request, and then to do the processing according to the appropriate method.

V. data volume processing request

Examples of the above requested data is transmitted via the url query in this way, but in reality will generally post request as request data in the request body, next take a look how the data in the request body.

Take a look at a column body on the postman:

You can see the data type in the request body or many, of these types of header by requesting Content-Typedetermined.

const http = require('http');
const urlParse = require('url');

const server = http.createServer();
const users = [];
server.on('request', (request, response) => {
  const { url, method, headers } = request;
  const { pathname } = urlParse.parse(url);
  const contentType = headers['content-type'];
  response.statusCode = 200;
  switch (pathname) {
    case '/user':
      switch (method) {
        case 'GET':
          response.end(JSON.stringify(users));
          break;
        case 'POST':
          if (contentType !== 'application/json') {
            response.statusCode = 400;
            response.end('error');
            break;
          }
          let requestBodyStr = '';
          request.on('data', (data) => {
            requestBodyStr += data.toString();
          });
          request.on('end', () => {
            const user = JSON.parse(requestBodyStr);
            users.push(user);
            response.end(JSON.stringify(user));
          });
          break;
        default:
          response.statusCode = 405;
          response.end('Method Not Allowed');
          break;
      }
      break;
    default:
      response.end("I don't know what you say.");
      break;
  }
});

server.listen(3000);

复制代码

Content-Type headers request can be obtained from the.

The key here is to compare:

let requestBodyStr = '';
request.on('data', (data) => {
    requestBodyStr += data.toString();
});
request.on('end', () => {
    const user = JSON.parse(requestBodyStr);
    users.push(user);
    response.end(JSON.stringify(user));
});
复制代码

To handle the data volume of requests, gotta get request to monitor data and end event.

The reason for this is that a large amount of data may request, than upload a file, if you put the data in a one-time deposit into memory, then the request is sent over hundreds of memory it burst. To solve this problem uses a node.js called "streaming" data structure to handle this situation. Analogy: There is a pond of water, it is unrealistic to complete a one-time pick, pick only the buckets, when the number of times you pick enough time so the pond water will be picked completely.

data event indicates that the data stream can already read

This event indicates that the end has come to the end of the stream, no data can be read.

In addition to these two than there is a error event indicates an error.

If you pick a bucket of endless, data event is triggered multiple times. end event will only be triggered once

Try this test:

const http = require('http');
const urlParse = require('url');

const server = http.createServer();
server.on('request', (request, response) => {
  const { url } = request;
  const { pathname } = urlParse.parse(url);
  response.statusCode = 200;
  switch (pathname) {
    case '/upload':
      let count = 0;
      request.on('data', () => {
        count += 1;
      });
      request.on('end', () => {
        response.end(`${count}`);
      });
      break;
    default:
      response.end("I don't know what you say.");
      break;
  }
});

server.listen(3000);

复制代码

Rar file transfer format by a form-data format. The file size is 65.2MB

result

node.js used 1354 times the water in the pond pick finished.

When the above functions are implemented, a simple http service was written.

Reproduced in: https: //juejin.im/post/5cf537f96fb9a07efb6970de

Guess you like

Origin blog.csdn.net/weixin_33735077/article/details/91462820