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端口:

console.log('Server is running at');

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

node server.js

Then open the browser and enter: you can see:

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


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

var url = request.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;
// <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){
            response.writeHead(200, {"Content-Type": "text/html;charset=UTF-8"});
              throw err;
server.listen(8080, '');

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>
    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;
        //发送请求'GET', '/data');

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:

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){
                response.writeHead(200, {"Content-Type": "application/json"});
                throw err;

Then after opening the browser , 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
Liao Xuefeng-http detailed

阅读 1.9k

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


893 声望
1.2k 粉丝
0 条评论


893 声望
1.2k 粉丝