当前位置:首页 > 前端 > 正文

node_http模块

// require语法 导入模块

//http,node内置模块
let http = require(‘http‘)

//创建一个服务器通道, 并传入回调函数
let server = http.createServer((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>‘);
})
// 让服务器监听8888端口:
server.listen(8888);

console.log(‘Server is running at http://127.0.0.1:8080/‘);
//在命令提示符下运行该程序,可以看到//以下输出:

//$ node hello.js 
//Server is running at http://127.0.0.1:8080/