使用node搭建服务器

客户端

服务器端 处理数据和业务逻辑

			请求
客户端	------------------> 服务器端
	  <------------------ 
	  		响应

使用node搭建服务器

// 创建服务器模块
const http = require('http');
// 创建一个服务器
const app = http.createServer();
// 监听客户端请求
app.on('request', (req, res) => {
    // 为了防止中文乱码
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf8'
    });
    // 响应
    res.end('<h1>hi, 小鲜肉</h1>');
});
// 监听端口
app.listen(8888);
console.log('服务器已启动,请访问localhost:8888');

// 使用这种方式也可以创建服务
const app = http.createServer((req, res) => {
    // 为了防止中文乱码
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf8'
    });
    // 响应
    res.end('<h1>hi, 小鲜肉</h1>');
});
// 监听端口
app.listen(8888);
console.log('服务器已启动,请访问localhost:8888');

请求报文

// 创建服务器模块
const http = require('http');
// 创建一个服务器
const app = http.createServer();
// 监听客户端请求
app.on('request', (req, res) => {
    // 请求报文
    req.headers
    // 请求地址
    req.url
    // 请求类型
    req.method
    // 为了防止中文乱码
    res.writeHead(200, {
        'content-type': 'text/html;charset=utf8'
    });
    // 响应
    res.end('<h1>hi, 小鲜肉</h1>');
});

响应报文

HTTP状态码

  1. 200 ok 请求成功
  2. 404 请求资源不存在
  3. 500 服务器错误
  4. 400 客户端请求有语法错误

内容类型

html文件:text/html

css文件:text/css

js文件:text/javascript

图片文件:image/jpeg

json文件:application/json

HTTP请求处理与响应处理

请求参数

get请求参数

参数会放置在浏览器地址栏中,可以借用url模块parse处理

get请求:

  1. 浏览器直接输入网址
  2. link href
  3. script src
  4. img src
  5. form表单
const http = require('http');
// 引入url模块
const url = require('url');
const app = http.createServer();
app.on('request', (req, res) => {
    // 第二个参数 true 可以把参数解析成对象形式
    let {query} = url.parse(req.url, true);
    res.end(`${query.username}-${query.pwd}`);
});

app.listen(7788);

post请求:

  1. 参数是被放在请求体中进行传输
  2. node处理post请求需要使用data和end两个事件
  3. 使用querystring模块
const http = require('http');
const qs = require('querystring')
const app = http.createServer();
app.on('request', (req, res) => {
    console.log(req.url); // 打印出原来的地址
    let postData = '';
    // 监听数据绑定事件
    req.on('data', (chunk) => {
        postData += chunk;
    });
    req.on('end', () => {
        console.log(postData); // username=admin&pwd=123456
        let {username, pwd} = qs.parse(postData); // {username: xxx, pwd: xxx}
    });
});

app.listen(7788);

路由

客户端请求地址与服务器端程序代码的对应关系

静态资源

服务器不需要处理,可以直接响应给客户端

动态资源

相同的请求地址不同的响应资源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值