一、处理 get 请求
-
nodejs 处理 http 请求
- get 请求和 queryString
- post 请求和 postData
- 路由
-
简单示例
// 1.导包 const http = require("http"); // 2.创建服务器 const server = http.createServer((reeq,res)=>{ res.writeHead(200,{'content-type':'text/html'}); res.end('<h1 style="color:red;">hello world</h1>'); }); // 3.开启监听服务器 server.listen(6500,()=>{ console.log('服务器已开启....6500'); })
-
nodejs 处理 get 请求
- get 请求,即客户端要向server端获取数据,如查询博客列表
- 通过 querystring 来传递数据,入 a.html?a=100&b=200
- 浏览器直接访问,就发送 get 请求
-
代码
// 1. 导包 const http = require('http'); const querystring = require("querystring"); // 2. 创建服务器 const server = http.createServer((req,res)=>{ console.log(req.method) // 请求方法,GET const url = req.url // 获取请求完整的 url console.log("url",url); req.query = querystring.parse(url.split('?')[1]); // 解析 querystring res.end(JSON.stringify(req.query)); }); // 3. 开启服务器监听 server.listen(6400,()=>{ console.log('服务器已开启') })
-
效果图
二、处理post请求
-
nodejs处理post请求
- post请求,即客户端要向服务端传递数据,如新建博客
- 通过 post data 传递数据
- 浏览器无法直接模拟,需要手写 js, 或者使用 postman
-
代码:
const http = require('http'); const server = http.createServer((req,res)=>{ if(req.method === 'POST'){ // 数据格式 console.log('req content-type:',req.headers['content-type']); // 接收数据 let postData = '' req.on('data',chunk =>{ postData += chunk.toString(); }); req.on('end',()=>{ console.log( 'postData:',postData) res.end('hello world') // 在这里返回,因为是异步 }) } }); server.listen(6600,()=>{ console.log('服务器已开启......') })
-
效果图