当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Node.js一次较完整的http请求过程展示

Node.js一次较完整的http请求过程展示

2018年11月01日  | 移动技术网IT编程  | 我要评论

node.js一次较完整的http请求过程展示

// 课时24request对象
// 课时25response对象 简单的http
// 相对来说比较完整的客户端服务请求和数据交互过程 
/*
* 搭建一个http的服务器,用于处理用户发送的http请求
* 需要使用node提供一个模块 http
*/



// 加载一个http模块
var http = require('http');

// 通过http模块下的createserver创建并返回一个web服务器对象
var server = http.createserver();


server.on('error', function(err) {
  console.log(err);
});

server.on('listening', function() {
  console.log('listening...');
});

server.on('request', function(req, res) {
  console.log('有客户端请求了');
  // console.log(req);
  // res.write('hello');
  //   res.writehead 最好写在正文之前
  res.writehead(200, 'linfei', {
    // 'content-type': 'text/plain' // 纯文本格式
    'content-type': 'text/html; charset=utf-8'
  });
  res.write('<h1>hello</h1>');
  res.end(); // 必须在最后调用,不能省略
})

server.listen(8080, 'localhost');

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网