nodejs foundation to build a simple web server with the http response module JSON, html

In the front-end development, most of them will want to get json data browser, let's set up a return json data server with the http module nodejs

 

var HTTP = the require ( "HTTP" ); 

var onRequest = function (Request, Response) { 
    the console.log ( "Request Received" ); 
    response.writeHead ( 200 is, { "the Content-the Type": " file application / JSON "}) ; // file application / JSON: the response is representative of JSON 
    // Response.Write ( "the returned content browser"); 
    var jsonObj = { 
        name: "Lili", 
        Job: "Coder", 
        Age: 18 is 
    } 
    response. End ( the JSON.stringify (jsonObj) ); // the json returned to the browser 
} 

var Server = http.createServer (onRequest);

//Finally, let the server listens on a port 
server.listen (3000, "127.0.0.1"); // You can also add a second parameter 127.0.0.1 represents the local 

console.log ( "Server Started ON localhost Port 3000"); / / add a server to start up tips

And then run to start the server node app

In the browser accessing localhost: 3000 found that the browser will display the json response data

 If json data browser is not formatted we need to install a browser plug-in JSON Formatter installed later, json data is formatted

 

 

 

Let's create a html web server response: Content-type of the value into text / html on the line

var http = require("http");

var onRequest = function(request,response){
    console.log("request received");
    response.writeHead(200,{"Content-Type":"text/html"});//application/json:代表响应的是json
    // response.write("传回浏览器的内容");
    var htmlFile = `<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>html</title>
        <style>
            div { 
                Color: Red; 
                font - size: 50px; 
            }
         </ style> 
    </ head> 
    <body> 
       <div> I is passed back html page </ div> from server 
    </ body> 
    </ html> `; 
    Response.End (htmlfile); // will json returned to the browser 
} 

var server = http.createServer (onRequest); 

// let the server listens on a port 
server.listen (3000, "127.0.0.1"); // also the second parameter may add 127.0.0.1 represents the local 

console.log ( "server started ON localhost Port 3000"); // add a server to start up tips

Then start the server page views localhost: 3000 found html page style will have what appear! ! !

 

Guess you like

Origin www.cnblogs.com/fqh123/p/11256707.html