美文网首页
Node中创建web服务与请求

Node中创建web服务与请求

作者: 前端开发小匠 | 来源:发表于2018-08-25 18:01 被阅读0次

    最近有空闲的时间就看看Node相关的,我觉得要真正掌握node得对node的一些核心模块比较熟悉才行。然后在去看其他的一些基于核心模块封装的框架(如 express/koa/egg等)或模块,这样也很好的理解框架中的内容。

    Node中如何创建 web server

    创建服务的步骤其实很简单,下面是Node官网中的一段代码。通过原生的方式创建了一个web server,这样就直接可以使用 http://127.0.0.1:3000 访问了。

    • 使用http模块 createServer方法创建一个服务;
    • createServer方法接收一个function作为参数,并进行请求处理,res.end('Hello World\n'); 处理请求,返回一个 Hello World 文本;
    • server监听 3000 端口。
    const http = require('http');
    
    const hostname = '127.0.0.1';
    const port = 3000;
    
    const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello World\n');
    });
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    

    以上是通过最原始的方式,当然也可以通过一些框架(如 express / koa / egg等)简化这些操作。

    // express 创建 web server
    var express = require('express');
    var app = express();
    
    app.get('/', function (req, res) {
      res.send('Hello World!');
    });
    
    app.listen(3000, function () {
      console.log('Example app listening on port 3000!');
    });
    
    // Koa创建web server
    const Koa = require('koa');
    const app = new Koa();
    
    app.use(async ctx => {
      ctx.body = 'Hello World';
    });
    
    app.listen(3000);
    

    Node创建HTTPS服务

    const https = require('https');
    const fs = require('fs');
    
    const hostname = '127.0.0.1';
    const port = 443;
    
    const options = {
      key: fs.readFileSync('./ssh/private.pem'), // 秘钥
      cert: fs.readFileSync('./ssh/full_chain.pem') // 证书
    };
    
    const server = https.createServer(options, (req, res) => {
      res.writeHead(200);
      res.end('hello world !!');
    });
    
    server.listen(port, () => {
      console.log(`The server is running at http://${hostname}:${port}/`);
    });
    

    Node中的请求

    通过上面创建 web server 过程可以看出,创建server的时候都对请求进行处理,否则创建web server也就意义不大了,所以创建了 server 就得使用。response 返回的内容总是会来自很多的地方,有些是直接返回一个固定的值,类似上面直接返回 Hello World 文本;有些返回的数据则是需要通过查询数据库存储的数据; 还有可能通过第三方的API对接, 下面就来看下如何请求第三方的API。

    老样子,先看看Node中原生的如何来实现:

    GET请求

    var http = require("http");
    
    var options = {
      "method": "GET",
      "hostname": "localhost",
      "port": "3000",
      "headers": {
        "Cache-Control": "no-cache"
      }
    };
    
    var req = http.request(options, function (res) {
      var chunks = [];
    
      res.on("data", function (chunk) {
        chunks.push(chunk);
      });
    
      res.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
      });
    });
    
    req.end();
    

    POST请求

    const postData = querystring.stringify({
      'msg': 'Hello World!'
    });
    
    const options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };
    
    const req = http.request(options, (res) => {
      console.log(`STATUS: ${res.statusCode}`);
      console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.');
      });
    });
    
    req.on('error', (e) => {
      console.error(`problem with request: ${e.message}`);
    });
    
    // write data to request body
    req.write(postData);
    req.end();
    

    原生的方式实现请求主要是通过 http.request 方法向第三方API发出请求。关于请求可以使用 request 模块 来简化请求的过程

    var request = require("request");
    
    var options = { method: 'GET',
      url: 'http://127.0.0.1:3000',
      headers: 
       { 'Postman-Token': 'd11b0b66-4ef1-4f2a-b83f-dd5bab3f6fe1',
         'Cache-Control': 'no-cache' } };
    
    request(options, function (error, response, body) {
      if (error) throw new Error(error);
    
      console.log(body);
    });
    

    下面的一个小 demo 就是通过 request 和 koa 相结合的。

    项目源码

    相关文章

      网友评论

          本文标题:Node中创建web服务与请求

          本文链接:https://www.haomeiwen.com/subject/vzugiftx.html