本文要做的是:
1.把接口
http://localhost:3000/api/list?number=100&username=zhangsan
中的参数取出来
2.把这个接口用接口测试工具测试,能正常执行。(使用http创建服务,并监听3000端口)
文中几个知识点:
split()是转成数组的方法。
从参数queryStr里面取出属性和属性值的时候,使用querySrt.split方法会不动不动报错,因为只有query有值,才会执行split split是数组转字符串,这个有时候会报错,解决方法是加个if
forEach()的用法
forEach是增强版的for循环,跟在数组后面,forEach里面的是一个箭头函数,箭头函数的参数就是数组中的每一项。array.forEach((item)=>{}),这个item就是数组里面的每一项。
完整代码和注释如下
// 引入http
const http = require("http")
// 创建服务
const server = http.createServer((req,res)=>{
// 请求的方法
const method = req.method
// 请求的路径
const url = req.url.split("?")[0]
// 获取url中携带的参数
// http://localhost:3000/api/list?keyword=nba&lang=en&number=100
const queryStr = req.url.split("?")[1]
// 参数获取到了,把参数取出来
const queryObj = {}
// 把获取到的queryStr转数组
// forEach是增强版的for循环,跟在数组后面,
// forEach里面的是一个箭头函数,箭头函数的参数就是数组中的每一项
if(queryStr){
// split是数组转字符串,这个有时候会报错,解决方法是加个if(){}
// 使用querySrt.split方法会不动不动报错,因为只有query有值,才会执行split
queryStr.split("&").forEach((item)=>{
// item是queryStr里面的每一项,也就是得到了所有的参数
// 参数以数组的方式赋值给item 比如 [number=100,age=18,username=zhangsan]
// 继续转,使用split("="),用等号分开,把属性和属性值取出来
const key = item.split("=")[0]/* number=100取出number */
const value = item.split("=")[1]/* number=100取出100 */
queryObj[key] = value /* 把属性和属性值都加到对象里面去 */
})
}
// 打印对象
console.log(queryObj);
// 判断接口
// res.end("this is listen.....")
if(url === "/api/list" && method === "GET"){
res.end(`this is list apt, ${queryObj.number}`)
}else if(url === "/api/create" && method ==="POST"){
res.end("this is create api")
}else{
res.end('this is error')
}
})
// 监听
server.listen(3000)
// 访问http://localhost:3000
console.log("请求响应成功,请访问http://localhost:3000");
测试结果
把http://localhost:3000/api/list?number=100
接口复制到接口测试工具,结果如下: