Introducing Http modules

By default, you have node.js installed. You can use

var http= require("http");
Copy the code

Introduce HTTP module;

Hello world

Implementing an HTTP server program in Node.js is very simple. We implement the simplest Web application that returns Hello World! For all requests. Create a new folder, apiDemo, create a new server.js folder, and say:

Var HTTP = require('http'); // Create the HTTP server and pass in the callback function: var server = http.createserver (function(request, response) {// The callback function receives request and response objects, and // gets the method and URL of the HTTP request: console.log(request.method +)':'+ request.url); // Write the HTTP response 200 to response and set content-type: text/ HTML: response.writeHead(200, {'Content-Type': 'text/html'}); // Write the HTML content of the HTTP response to response: response.end('Hello world! '); }); // Let the server listen on port 8080: server.listen(8080); console.log('Server is running at http://127.0.0.1:8080/');
Copy the code

Then run at the command prompt (CMD, etc.) in the current directory:

node server.js
Copy the code

Then open your browser and type: http://127.0.0.1:8080/ to see:

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

GET: /
GET: /favicon.ico
Copy the code

The main things to know are:

http.createServer(function(request, response){}) 
Copy the code

It creates an HTTP service that passes a callback function with two parameters (request, response). Request is a request object, and response is a response object. You can retrieve some information about the request header from the request object, such as: Request.url – Returns the request path after a successful response: Response.writeHead ()———— sends a response header to the request response.end(‘ XXX ‘)———— returns XXX reference Nodez Chinese-http

routing

We want to return the index.html of the current directory when we visit http://127.0.0.1:8080/. If request.url === ‘/’ is true, we can confirm that we are requesting the root directory.

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

We can create a service that uses Response.end (‘Hello world! ‘); Return “Hello world!” . If you want to return a file, you need a node.js module called the FS file system. This module is used to process files in Node.

var fs= require('fs');
Copy the code

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...>
});
Copy the code

The callback function takes two arguments (err, data), where data is the contents of the file and is returned in binary form.

Then we can write code that returns the index.html file when accessing the root directory

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("Error"); }}); server.listen(8080,'127.0.0.1');
Copy the code

Create a new index.html file in the current directory, where we can write an Ajax request. Later we will click the button to make an Ajax request for 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; }} // Send the request http.open('GET'.'/data');
        http.send();
    }
    </script>
Copy the code

This code makes an AJSX request to /data when a button is clicked,

Implement a simple API interface

Since we can return HTML files when accessing the root directory, we can set a URL of our own and return a set of JSON data to it when requesting this URL. The data would normally be read from the database. In this case, just simulate a set of JSON data. Create a new data.json file in the current directory:

{"name": "Nicholas Ding * Zhao Si"}
Copy the code

So the current directory structure is:

Json is returned when the requested URL is /data:

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; }})}Copy the code

If the server receives the request, it will determine the url === ‘/data’. When the server receives the request, it will determine the url === ‘/data’. It will then return data.json to us.

The final implementation is to click the button to appear nicola ding * Zhao four, GItHub source: node-apidemo Reference: Liu Xiao-feng HTTP detail explanation of node-fs