当前位置:网站首页>[Nodejs]Nodejs创建一个简单的服务器
[Nodejs]Nodejs创建一个简单的服务器
2022-07-19 05:05:00 【小小_xiuxiu】
运用Nodejs创建一个简单的应用,首先需要搞清楚一个问题:
Nodejs应用由哪几部分组成?
1、require指令引入Nodejs模块
2、创建一个服务器,用于监听客户端的请求
3、接受请求与响应请求的模块
接下来就是根据以上三个部分来创建一个Nodejs应用
1、引入require模块
//server.js
var http = require('http');
2、创建服务器
此处创建了一个HTTP服务器并监听8000端口
//server.js
http.createServer(function(request,response) {
// something to response
}).listen(8000);
3、接受请求与响应请求
此处设置了响应头部和响应内容,当客户端访问localhost:8000的时候,服务端会接收到请求并返回响应内容 后端服务创建成功。
//server.js
http.createServer(function(request,response) {
response.writeHead(200,{
'Content-Type': 'text/plain;charset=utf-8'});
response.end(JSON.parse(JSON.stringify('后端服务创建成功')));
}).listen(8000);
最后,执行node命令 node server.js 就可以启动http服务器。
如下图:
如此,一个Nodejs简单应用创建成功。
边栏推荐
猜你喜欢
随机推荐
详解全排列问题(不同的解法的不同输出结果)
Shell Scripting
Chapter 58: vs debugging appears "coverage.... yes /n: no /a: all)
三角形问题最坏情况测试测试用例
Three piece chess game
巩固复习之指向函数指针数组的指针、回调函数
Consolidate and review the pointers and callback functions pointing to the function pointer array
数组的 reduce方法
Pytorch target detection competition (I) data analysis
Explain the full permutation problem in detail (different output results of different solutions)
学习日记1
[Day.2]约瑟夫环问题,如何用数组代替循环链表(详解)
冒泡排序思想及实现
A long detailed explanation of C language dynamic memory management
【学习笔记】Unreal(虚幻)4引擎入门(三)
第七十五篇:学术论文写作技巧
Dynamic memory management
4000 words, let you understand recursion and its example practice (C language, with pictures)
Using C to realize three versions of address book
Common network vendor MIB library files