nodeJs编写的简单服务器

 

nodeJs 远程服务器的部署和简单静态Web服务器

 一、简单的nodeJs写的 http 服务器

1.先Hello world,创建最简单的 Node 服务器(server.js)

const http = require("http");

http.createServer(function(request, reponse) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

执行: 

node server.js

1. var http = require("http")  表示请求NodeJs自带的 http 模块,并赋值给 http 变量

2.  http.createServer()  会返回一个对象,这个对象有一个 listen 方法,这个方法有一个Number类型的参数,该参数指定了HTTP服务器监听的端口号

3. 所以本段代码 会开启一个监听 8888 端口的服务器,我们可以通过打开浏览器,访问 http://localhost:8888/  来连接该服务器,我们会看到网页上写着 “Hello World”

 

二、事件驱动和回调:

上面的代码也可以如此编写:(即onRequest函数作为参数传递给 http.createServer() 

复制代码
const http = require("http");
function onRequest(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
复制代码

onRequest函数会在 http.createServer() 方法执行时的特定时间点去调用(即某个事件发生时,才会执行——事件驱动的回调

回调函数的目的: 当我们使用 http.createServer 方法的时候,我们当然不只是想要一个侦听某个端口的服务器,我们还想要它在服务器收到一个HTTP请求的时候做点什么

执行上面的代码(node server.js )终端会输出上图的  Server has started.  文本;

再打开 http://localhost:8888/  路径,终端会输出上图的 Request received. 文本,输出两次(因为还会访问一次http://localhost:8888/favicon.ico);

这就是事件驱动,访问时(事件发生)才会调用。

 

三、服务器相关:

1. onRequest函数被调用时,request 和 response 作为参数会被传入;

2. request 和 response 是对象,可以使用它们的方法来 处理HTTP请求的细节,也可以 响应请求 (即给发请求的浏览器返回数据);

3. 上面的代码:

收到请求时,

使用 response.writeHead() 函数发送一个HTTP状态(200)和HTTP头的内容类型(content-type),

使用 response.write() 函数在HTTP相应主体中发送文本“Hello World"。

调用 response.end() 完成响应。

 暂时未使用 request ,request中放的是请求时的携带的参数

 

四、node中模块的导入导出

复制代码
//导入http模块,并使用
const http = require("http");
...
http.createServer(...).listen(8888);
//此处使用http变量来接受赋值,也可以使用其他变量


//导出自己的模块start,我们把它写在server.js中
function start() {
   ...   
}

exports.start = start;

//导入自己的模块start
const server = require("./server");

server.start();
复制代码

 

posted @   南歌子  阅读(2944)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示