资讯接口
发布时间 2023-06-02 17:33:12作者: GTK
习题链接
消失的 Token
课程列表
使用node来编写一个简单API接口
当我访问/news要返回一个数据对象给我
当我访问其他的路径均返回404
关键点
- node基础知识点 http模块
- 使用require导入http模块
- 使用 http 模块中的createServer方法来创建 HTTP 服务器
- 在req中的url属性进行设置API接口,根据url的不同来返回不同的数据
- res.end与res.send的基本区别
- res.end()只能返回字符串数据,如果返回的数据不是字符串,可以使用JSON.stringify(数据对象)进行转换成字符串
- res.end()执行只后就等同于这个api结束了,后面的代码不会再执行了。
- res.send() 可以返回不同的数据类型,并不限制于字符串,能够自动设置合适的响应头
- res.send() 执行之后还能够继续执行其他的代码,甚至还可以再次发送res.send()方法
- 扩展在这里其实也可以使用express框架来编写
实现过程 && 完整的代码
- 完整code
const http=require('http')
const app = http.createServer((req,res)=>{
res.setHeader("Content-type", "text/html;charset=utf8");
if (req.url == '/news') {
let data = [
{
"channelId": "5572a108b3cdc86cf39001cd",
"name": "国内焦点"
},
{
"channelId": "5572a108b3cdc86cf39001ce",
"name": "国际焦点"
}
];
res.send(JSON.stringify(data));
} else {
res.end('404');
}
})
app.listen(8080,()=>{});