Use Node.js to write a simple api interface

九旬
中文

Introduce Http module

By default you have installed Node.js
Http module is built in Node;
can use

var http= require("http");

Introduce http module;

Hello world

It is very simple to implement an HTTP server program with Node.js. We implement one of the simplest web programs,
For all requests it, return Hello world !, create a new folder apiDemo inside a new server.js writes:

// 导入http模块:
var http = require('http');
// 创建http server,并传入回调函数:
var server = http.createServer(function (request, response) {
    // 回调函数接收request和response对象,
    // 获得HTTP请求的method和url:
    console.log(request.method + ': ' + request.url);
    // 将HTTP响应200写入response, 同时设置Content-Type: text/html:
    response.writeHead(200, {'Content-Type': 'text/html'});
    // 将HTTP响应的HTML内容写入response:
    response.end('Hello world!');
});

// 让服务器监听8080端口:
server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

Then run in the current directory command prompt (cmd, etc.), enter:

node server.js

Then open the browser and enter: http://127.0.0.1:8080/ you can see:
91544605447_.pic.jpg

At the same time, you can see the information printed in the command line:

GET: /
GET: /favicon.ico

The main things to understand are:

http.createServer(function(request, response){}) 

Its function is to create an http service, which passes a callback function, and the function contains two parameters (request, response).
Where request is the request object, and response is the response object.
Some information of the request header can be obtained according to the request request.url request path
After successful response:
response.writeHead() ———— Send a response header to the request
response.end('xxx') ————Response successfully returns xxx
reference Nodez Chinese website-HTTP

routing

We want to return the index.html of the current directory when http://127.0.0.1:8080/
In other words, when request.url === '/' is true , it can be determined that the current request is the root directory.

var url = request.url;
console.log(url);
// '/'

We can create a service and use response.end('Hello world!'); to return "Hello world!". If you want to return a file, you need to use a module of Node.js- fs file system .
It is a file processing module in Node. First introduced:

var fs= require('fs');

You can use fs.readFile() to read the file

fs.readFile('./index.html', function(err, data)  {
  if (err) throw err;
  console.log(data);
// <Buffer 3c 21 44 4f 4...>
});

The callback function has two parameters (err, data), where data is the content of the file and is returned in binary form.

Then we can write the code, when we visit the root directory, return the index.html file

var http= require('http');
var fs= require('fs');
var server= http.createServer(function(request, response){
    var url = request.url;
    if(url === '/'){
        fs.readFile('./index.html', function(err, data){
          if(!err){
            response.writeHead(200, {"Content-Type": "text/html;charset=UTF-8"});
            response.end(data)
          }else{
              throw err;
          }
        });
    }else{
        console.log("错误");
    }
});
server.listen(8080, '127.0.0.1');

Then create a new index.html in the current directory, where we can write an ajax request, after a while we click the button to realize the ajax request a set of data:

 <div id="box">看不到看不到</div>
    <button onclick="success()">我是按钮</button>
    <script>
    function success(){
        var http= new XMLHttpRequest();
        http.onreadystatechange= function(){
            if(http.status == 200 && http.readyState == 4){
                var msg= http.responseText;
                var box= document.getElementById('box');
                box.innerHTML= JSON.parse(msg).name;
            }
        }
        //发送请求
        http.open('GET', '/data');
        http.send();
    }
    </script>

This code is to initiate an ajsx request /data when the button is clicked.

Implement simple API interface

Since the html file can be returned when the root directory is accessed, we can set a url ourselves, and when the url is requested, we will return a set of json data to it. Normally, these data should be read from the database. Only a set of json data is simulated here. Create a new data.json in the current directory:

{"name": "尼古拉丁 * 赵四"}

So the current directory structure is:
41544775041_.pic.jpg

Then we can judge in server.js, when the requested url is /data , data.json is returned:

if(url === '/data'){
        fs.readFile('./data.json', function(err, data){
            if(!err){
                response.writeHead(200, {"Content-Type": "application/json"});
                response.end(data);
            }else{
                throw err;
            }
        })
    }

Then after opening the browser http://127.0.0.1:8080 , the index.html page will appear. Clicking the button that appears will trigger an /data . When server.js receives the request, it will judge url === '/data' , and then it will return data.json Give us.

The final realization is to click the button to appear Nicholas * Zhao four ,
GItHub source code: node-apiDemo
reference:
Liao Xuefeng-http detailed
Node-fs

阅读 1.9k

九旬的博客
关注我,每周输出一篇前端技术文章, 博客地址:[链接]

关注我,每周输出一篇前端技术文章,

893 声望
1.2k 粉丝
0 条评论

关注我,每周输出一篇前端技术文章,

893 声望
1.2k 粉丝
文章目录
宣传栏