如何用nodejs搭建web服务器

2025-05-10 04:08:24
推荐回答(1个)
回答1:

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。 Node.js 使用了一个事件驱动、非阻塞式
I/O 的模型,使其轻量又高效。Node.js 的包管理器
npm,是全球最大的开源库生态系统。(nodejs官网上的介绍),正如官网上介绍的那样,nodejs确实很牛!怎么个牛法?看看下面的代码就知道了。
//引入http模块
var http = require("http");
//设置主机名
var hostName = '127.0.0.1';
//设置端口
var port = 8080;
//创建服务
var server = http.createServer(function(req,res){
res.setHeader('Content-Type','text/plain');
res.end("hello nodejs");

});
server.listen(port,hostName,function(){
console.log(`服务器运行在http://${hostName}:${port}`);
});
短短几行代码就把一个简单的web服务器搭建完成了,为了验证效果,我们在浏览器请求