Node学习(一)node利用自带的http服务编写服务器程序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012832088/article/details/81735827

node.js利用自带的HTTP模块服务编写服务器程序

>利用node.js自带的HTTP模块,开发HTTP服务器程序。避免应用程序直接与HTTP协议打交道,只需操作request和response对象即可。

http模块

request对象封装了HTTP请求;response封装了HTTP响应。

利用http模块实现一个http服务器,创建一个helloworld.js

'use strict';
// 导入http模块:
var http = require('http');

// 创建http server,并传入回调函数:
var server = http.createServer(function (request, response){

// 回调函数接收request和response对象,
// 获得HTTP请求的method和url:

console.log(request.method + ': ' + request.url);

// 将HTTP响应200写入response, 同时设置Content-Type: text/html:
response.writeHead(200, {'Content-Type': 'text/html'});

// 将HTTP响应的HTML内容写入response:
response.end('<h1>Hello world!</h1>');
});

// 让服务器监听8080端口:
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');

猜你喜欢

转载自blog.csdn.net/u012832088/article/details/81735827