您的位置:首页 > Web前端 > Node.js

使用node搭建服务器

2020-06-29 04:33 711 查看

客户端

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

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

使用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);

路由

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

静态资源

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

动态资源

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: