测试的接口
http://localhost:3000/api/list?number=4
当使用postman测试接口时,处除了能正常执行,我们需要返回响应的数据。
响应头,包含状态码和返回的格式,这里是固定写法
res.writeHead(200, {
"Content-type": "application/json",
});
响应体,里面包含错误码和返回的数据
const responseBody = {
errno: 0,/* 错误码err number为0,就是正常返回 */
data: [
{ id: 1, user: "张三", content: "张三真帅" },
{ id: 2, user: "李四", content: "李四真帅" },
{ id: 3, user: "王五", content: "王五真帅" },
{ id: 4, user: "赵六", content: "赵六真帅" },
],
};
res.end()只能返回字符串,所有需要把响应体对象转成字符串,使用JSON.stringify()
res.end(JSON.stringify(responseBody))
index.js完整代码如下
// index.js
const http = require("http");
// 引入自带的querystring,这是一个方法
const qurerystring = require("querystring");
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
// 获取请求的路径
const path = url.split("?")[0];
// 获取请求的querystring
const queryStr = url.split("?")[1];
// querystring转对象
// 用引入的qureystring模块 把split转出来的参数数组转成字符串 qurerystring.parse(queryStr)
//把这转出来的放到对象里面去
const queryObj = qurerystring.parse(queryStr);
if (path === "/api/list" && method === "GET") {
// res.end(`您正在请求留言板列表接口! 将返回${queryObj.number}条留言!`);
// 返回的内容
// 首先定义响应头,包括状态码和返回的类型(这里是固定写法)
res.writeHead(200, {
"Content-type": "application/json",
});
// 定义返回的响应体,包含错误码和返回的内容
const responseBody = {
errno: 0,/* 错误码err number为0,就是正常返回 */
data: [
{ id: 1, user: "张三", content: "张三真帅" },
{ id: 2, user: "李四", content: "李四真帅" },
{ id: 3, user: "王五", content: "王五真帅" },
{ id: 4, user: "赵六", content: "赵六真帅" },
],
};
// 定义好了响应头和响应体,现在返回响应的数据
// res.end()只能返回字符串,需要把响应体转成字符串,再放到res.end()里面
res.end(JSON.stringify(responseBody));
} else if (url === "/api/create" && method === "POST") {
res.end("this is create api menthod is POST");
} else {
res.end("别瞎写! [○・`Д´・ ○]");
}
});
server.listen(3000);
console.log("http请求已经被监听, 3000端口, 请访问: http://localhost:3000");