nodejs基础 用http模块 搭建一个简单的web服务器 响应JSON、html

前端在开发中,大多会想浏览器获取json数据,下面来用nodejs中的http模块搭建一个返回json数据的服务器

var http = require("http");

var onRequest = function(request,response){
    console.log("request received");
    response.writeHead(200,{"Content-Type":"application/json"});//application/json:代表响应的是json
    // response.write("传回浏览器的内容");
    var jsonObj={
        name:"lili",
        job:"coder",
        age:18
    }
    response.end(JSON.stringify(jsonObj));//将json传回浏览器
}

var server = http.createServer(onRequest);

//最后让服务器监听一个端口
server.listen(3000,"127.0.0.1");//还可以加第二个参数 127.0.0.1代表的是本地

console.log("server started on localhost port 3000");//加一个服务器启动起来的提示

然后运行 node app  启动服务器

在浏览器访问localhost:3000   发现浏览器会显示 响应的json数据

 如果浏览器的json数据没有 格式化  我们需要装一个浏览器插件 JSON Formatter   安装过之后,显示的json数据就是格式化的

下面来创建一个响应html的web服务器:将Content-type的值改成text/html就行

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>我是从服务器传回来的html页面</div> 
    </body>
    </html>`;
    response.end(htmlFile);//将json传回浏览器
}

var server = http.createServer(onRequest);

//最后让服务器监听一个端口
server.listen(3000,"127.0.0.1");//还可以加第二个参数 127.0.0.1代表的是本地

console.log("server started on localhost port 3000");//加一个服务器启动起来的提示

然后启动服务器  页面访问localhost:3000   发现会出现html页面样式什么的都有!!!

猜你喜欢

转载自www.cnblogs.com/fqh123/p/11256707.html