使用node.js搭建基本服务器

77 阅读1分钟
const http = require("http")
const fs = require("fs")
const url = require("url")

const server = http.createServer()
//监听并执行在端口8000上的请求
server.listen(8000, function () {
    console.log('listening on http://localhost');
})
//监听页面的请求
server.on('request', (request, res) => {
    if(request.method === 'GET') {
        const parsedUrl = url.parse(request.url, true)
        const query = parsedUrl.query
        console.log(query.id);
        // res.writeHead(200, { 'Content-Type': 'application/json' })
        // res.end(JSON.stringify(query))
    }
    if (request.url === "/") {
        fs.readFile("./index.html", function (err, data) {
            if (err) throw err;
            res.end(data)
        })      
    }
    if (request.url === "/1.png") {
        fs.readFile("./1.png", function (err, data) {
            if (err) throw err;
            res.end(data)
        })      
    }
});