- 服务端识别“流”
let bodyStr = '';
req.on('data', chunk => { // 服务端怎么去识别流,并接收数据
// chunk为流的每一段数据
bodyStr = bodyStr + chunk.toString();
});
- 服务端识别流的完成
req.on('end', () => { // 服务端怎么知道流完了
console.log('bodyStr is', bodyStr)
res.end('接收完成');
})
- 完整代码:从模拟创建留言之后看
const http = require('http');
const querystring = require('querystring');
// req: request, res: response
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method
const path = url.split('?')[0]
const queryStr = url.split('?')[1] //a=1&b=2
// 简化版解析quertStr
const query = querystring.parse(queryStr)
// 定义路由,模拟获取留言板列表:访问该路由则返回的内容
// 返回结果
const result = {
errno: 0,
data:[
{user:'张三', content: '留言1'},
{user:'李四', content: '留言2'}
]
}
if (path === '/api/list' && method === 'GET') {
res.writeHead(200, {'Content-type': 'application/json'});
// 为什么要用JSON.stringfy转换成字符串?因为end()里只能接字符串,所以把对象转换成字符串
res.end(JSON.stringify(result)
)
}
// 定义路由,模拟创建留言
if (path === '/api/create' && method === 'POST') {
let bodyStr = '';
req.on('data', chunk => { // 服务端怎么去识别流,并接收数据
// chunk为流的每一段数据
bodyStr = bodyStr + chunk.toString();
});
req.on('end', () => { // 服务端怎么知道流完了
console.log('bodyStr is', bodyStr)
res.end('接收完成');
})
// const result = {
// error: 0,
// message: '创建成功'
// }
// res.writeHead(200, {'Content-Type': 'application/json'})
// res.end(JSON.stringify(result));
return;
}
})
server.listen(3000); // 可以监听http的请求了
console.log('http请求已经被监听,3000端口');
- 用POSTMAN模仿前端给服务器发送请求
- 返回结果
6. 优化:将接收的字符串格式转换成json格式
const body = JSON.parse(bodyStr) // 转换成json格式
- 完整代码如下:
const http = require('http');
const querystring = require('querystring');
// req: request, res: response
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method
const path = url.split('?')[0]
const queryStr = url.split('?')[1] //a=1&b=2
// 简化版解析quertStr
const query = querystring.parse(queryStr)
// 定义路由,模拟获取留言板列表:访问该路由则返回的内容
// 返回结果
const result = {
errno: 0,
data:[
{user:'张三', content: '留言1'},
{user:'李四', content: '留言2'}
]
}
if (path === '/api/list' && method === 'GET') {
res.writeHead(200, {'Content-type': 'application/json'});
// 为什么要用JSON.stringfy转换成字符串?因为end()里只能接字符串,所以把对象转换成字符串
res.end(JSON.stringify(result)
)
}
// 定义路由,模拟创建留言
if (path === '/api/create' && method === 'POST') {
//获取传过来的数据是什么格式
console.log('req content-type', req.headers['content-type'])
const reqType = req.headers['content-type'];
let bodyStr = '';
req.on('data', chunk => { // 服务端怎么去识别流,并接收数据
// chunk为流的每一段数据
bodyStr = bodyStr + chunk.toString();
});
req.on('end', () => { // 服务端怎么知道流完了
if (reqType === 'application/json') {
console.log('bodyStr is', bodyStr) // 字符串格式
const body = JSON.parse(bodyStr) // 转换成json格式
console.log('body is', body) // 对象格式
}
res.end('接收完成');
})
// const result = {
// error: 0,
// message: '创建成功'
// }
// res.writeHead(200, {'Content-Type': 'application/json'})
// res.end(JSON.stringify(result));
return
}
})
server.listen(3000); // 可以监听http的请求了
console.log('http请求已经被监听,3000端口');