Home >Web Front-end >JS Tutorial >Instructions for using the http.createServer method in node.js_node.js

Instructions for using the http.createServer method in node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:27:123220browse

Method description:

This function is used to create an HTTP server and use requestListener as the listening function for the request event.

Grammar:

Copy code The code is as follows:

http.createServer([requestListener])

Since this method belongs to the http module, the http module needs to be introduced before use (var http= require("http") )

Receive parameters:

requestListener request processing function, automatically added to the request event, the function passes two parameters:

req request object. If you want to know what attributes req has, you can check "http.request attribute integration".

res Response object, the response to be made after receiving the request. If you want to know what attributes res has, you can check "http.response attribute integration".

Example:

In the example, res specifies the response header, the response body content is node.js, and ends with end.

Finally call the listen function to listen on port 3000.

Copy code The code is as follows:

var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-type' : 'text/html'});
res.write('

Node.js

');
res.end('

Hello World

');
}).listen(3000);

Source code:

Copy code The code is as follows:

exports.createServer = function(requestListener) {
Return new Server(requestListener);
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn