[Node.js]Web Server

"use strict";
const fs = require("fs");
const http = require("http");
const url = require("url");
const data=fs.readFile(`${__dirname}/1.json`, "utf-8");
const p=JSON.parse(data);           //json转字符串

const server = http.createServer((req, res) => {          //生成服务器
    const pathName = req.url;           //获取路径名称
    if (pathName === "/" || pathName === "/overview") {
        res.end("Overview!");
    } else if (pathName === "/product") {
        res.end("Product!");
    } else if(pathName === "/api"){
            res.writeHead(200,{
                "Content-type":"application/json"
            });
            res.end(data);          //res.end只能放字符串
    }else{
        res.writeHead(404, {
            "Content-type": "text/html"
        });
        res.end("<h1>abaaba</h1>")
    }
});

// 服务器监听
server.listen(8000, "127.0.0.1", () => {
    console.log("Listening...")
});

猜你喜欢

转载自blog.csdn.net/weixin_66896881/article/details/128539944