node构建服务器
We have been through enough stuff on NODE JS in my previous articles and now we are ready to build a fully functional web server listening to requests on the designated port number.
在之前的文章中,我们已经对NODE JS进行了足够的介绍,现在,我们准备构建一个功能完整的Web服务器,以侦听指定端口号上的请求 。
Code:
码:
var http=require('http');
function myfunc(request,response){
console.log(" user made a request at "+ request.url );
response.writeHead(200,{ "Context-Type":"text/plain"});
response.write("welcome to 4000 ");
response.end();
}
http.createServer(myfunc).listen(4000);
console.log("server made");
Output screenshot 1
输出屏幕截图1
![Node JS | Build web server output 1](https://www.includehelp.com/node-js/Images/build-web-server-output-1.jpg)
Output screenshot 2
输出屏幕截图2
![Node JS | Build web server output 2](https://www.includehelp.com/node-js/Images/build-web-server-output-2.jpg)
Explanation of the code:
代码说明:
For building web server we first need to import http module inbuilt in Node JS which is done in line number 1.
为了构建Web服务器,我们首先需要导入Node JS中内置的http模块,此操作在第1行中完成。
Then in line number 10, createServer method of http is being used to designate a port number for listening requests. Here I have used 4000.
然后在第10行中,使用http的createServer方法指定用于侦听请求的端口号。 在这里我用了4000。
We have passed a function reference i.e. myfunc as an argument in createServer method that means whenever user will go to localhost 4000 via any browser this function will be called.
我们在createServer方法中传递了一个函数引用,即myfunc作为参数,这意味着每当用户通过任何浏览器进入localhost 4000时,都会调用此函数。
In line number 3, I have defined function myfunc. It has two parameters request and response that are inbuilt in http module.
在第3行中,我定义了函数myfunc 。 它具有http模块中内置的两个参数request和response 。
The request has info regarding the request made by the user like here I have used request url.
该请求具有有关用户提出的请求的信息,例如此处我使用了请求url。
Likewise, Response is used to generate require response or output.
同样,响应用于生成需求响应或输出。
First, we mention the type of response and then the content of the response.
首先,我们提到响应的类型,然后是响应的内容。
In today’s era web development is in immense demand, thus every Software industry enthusiast ought to have knowledge regarding it.
在当今时代,Web开发的需求量很大,因此,每个软件行业爱好者都应该对此有所了解。
This article provides an initial step towards web development career.
本文提供了迈向Web开发事业的第一步 。
翻译自: https://www.includehelp.com/node-js/building-web-server.aspx
node构建服务器