优秀的编程知识分享平台

网站首页 > 技术文章 正文

nodejs入门教程之简单的http服务器(四)

nanyue 2024-07-18 22:05:45 技术文章 11 ℃

nodejs 实现简单的http服务

前两章我们学习了模块和面向对象,那么们就用这两个知识点完成一个简单的http服务。服务满足以下功能

  • 在8080端口启动服务器
  • 前端发一个请求到服务器上
  • 服务端收到请求时打印“request coming” 日志
  • 日志打印完成后返回“hello word”给前端

创建服务器类

// Application.js
const http = require("http")
class Application {
    /**
     *  创建服务
     * @param port 服务运行的端口号
     */
    constructor(port) {
        this.port = port
        this.server = null;
    }

    boot() {
        this.server = http.createServer(((req, res) => {
            console.log('request coming')// 收到请求打印日志
            res.writeHead(200);
            res.end("hello world") // 返回前端
        }));
        this.server.listen(this.port, () => {
            console.log("server start success")
        })
    }
}


module.exports = Application;

require("http") 这个模块是nodejs系统内置的http模块http.server是一个基于事件的HTTP服务器,内部是由c++实现的,接口由JavaScript封装

实例化服务器对象并启动

//index.js
const Application = require("./Application");
const app = new Application(8080)
app.boot()

实例化服务器对象,实例化的时候传入它需要启动的端口号

启动nodejs进程

node ./index.js


控制台输出结果“server start success”说明服务成功启动

测试服务

浏览器输入“http://localhost:8080”可以看到返回

这时候说明我们的程序已经成功地启动了,其中localhost为本机地址,8080为服务启动的端口号

最近发表
标签列表