使用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状态码
- 200 ok 请求成功
- 404 请求资源不存在
- 500 服务器错误
- 400 客户端请求有语法错误
内容类型
html文件:text/html
css文件:text/css
js文件:text/javascript
图片文件:image/jpeg
json文件:application/json
HTTP请求处理与响应处理
请求参数
get请求参数
参数会放置在浏览器地址栏中,可以借用url模块parse处理
get请求:
- 浏览器直接输入网址
- link href
- script src
- img src
- 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请求:
- 参数是被放在请求体中进行传输
- node处理post请求需要使用data和end两个事件
- 使用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);
路由
客户端请求地址与服务器端程序代码的对应关系
静态资源
服务器不需要处理,可以直接响应给客户端
动态资源
相同的请求地址不同的响应资源
相关文章推荐
- 使用node搭建静态文件服务器
- 使用Node.js搭建本地服务器
- 用node.js搭建服务器,模拟返回json数据供客户端get,post请求使用
- 使用node.js搭建服务器
- 从新修订了一下安装新版koa2 linux(centOS)下搭建node服务器, 使用koa2搭建项目
- nodejs express服务器搭建和使用教程
- 使用express快速搭建一个node服务器
- 建立一个node.js服务器(使用express搭建第一个Web环境)
- 使用node.js在sublime text3搭建服务器
- 使用node.js搭建本地服务器
- 使用Express搭建Node.js服务器
- 使用Node.js搭建静态资源服务器
- 如何使用Node.js搭建本地服务器连接本地数据库
- 使用Node.js搭建静态资源服务器
- 使用 Node.js 搭建 Web 服务器
- 【node.js】使用node.js搭建一个本地web服务器
- 使用node.js搭建服务器(详解)
- Nodejs如何创建服务器???配置服务???需要引用第三方框架???简单使用express框架搭建node服务
- 使用 Node.js 和 Express.js 搭建简易 HTTP/2 服务器