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

nodejs 实现简单的http服务

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

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

1 创建服务器类

// 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封装

2 实例化服务器对象并启动

//index.js

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

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

3 启动nodejs进程

node ./index.js

输出
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vVYYymbH-1624949306795)(file:///C:/Users/tw949/.config/joplin-desktop/resources/bf5bfbdb0d4c448498a589765c3ed4a7.png)]

4 测试服务

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

在这里插入图片描述

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TristanWong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值