联系QQ 284710375
首页 > 技术分享 > NodeJS
收藏

nodejs引入http模块,创建服务器2023-03-09 23:52:30

大潇博客 原创文章,转载请标明出处

NodeJS组成:

1、引入required模块,可以使用require指令载入nodejs模块

2、创建服务器,服务器可以监听客户端的请求,类似Apache、Nginx等http服务器

3、接收请求与响应请求,服务器很容易创建,客户端可以使用浏览器发送HTTP请求,服务器接受后返回响应数据


使用浏览器访问NodeJS程序,需要引入http模块实现,首先创建一个js文件,添加以下代码:

//引入http模块,用来创建服务器

var http = require('http');

//创建服务器

http.createServer(function(request, response) {

//状态码:200

//返回数据类型:文本

//返回的编码是:utf-8

response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});

response.write('NodeJS...\n');

response.write('欢迎学习NodeJS\n');

response.end("Hello World\n"); //不能缺失

}).listen(8000); //监听的端口,浏览器使用http://localhost:8000访问

//打印提示信息,这个不是必须的,仅用来自己个儿看

console.log('第一个NodeJS程序');

保存后,开发cmd进入文件所在目录,输入“node 文件名”,通过node终端加载这个文件:

nodejs加载文件.png

浏览器访问:

浏览器访问NodeJS.png


上面的代码,还可以通过如下方式实现:

//加载http模块以创建http服务器

var http = require('http');

//创建响应函数

function onRequest(request, response) {

response.writeHead(200, {"Content-Type": "text/plain"});

response.end("Hello World11\n");

}

//配置HTTP服务器

var server = http.createServer(onRequest);

//监听8000端口,ip默认为127.0.0.1

server.listen(8000);


打赏

上一篇:NodeJS入门

下一篇:NPM基本使用方法

阅读排行

大家都在搜

博客维护不易,感谢你的肯定
扫码打赏,建议金额1-10元
  • 15601023311