使用 Node.js Express 创建 API 路由获取网站总数
使用 Node.js Express 创建 API 路由获取网站总数
本文将介绍如何使用 Node.js Express 框架创建一个 API 路由,用于获取网站总数数据。
首先,我们需要一个函数来获取网站总数,假设这个函数已经定义在 ./Site 文件中,名为 getSortedSitesData。
import { getSortedSitesData } from './Site';
export async function total() {
const allPostsData = await getSortedSitesData()
const formattedPosts = allPostsData.map(post => {
return {
...post,
date: post.date.toString()
};
});
// Assume there are 100 posts in the database
const totalPosts = formattedPosts.length
console.log(`网站总数:${totalPosts}`);
return { totalPosts };
}
创建 API 路由
接下来,我们需要使用一个 Node.js 框架来创建 API 路由。常见的框架有 Express、Koa、Hapi 等等。这里以 Express 为例。
-
安装 Express:
npm install express
2. **创建路由文件:**
创建一个新的文件,例如 `api.js`,并在其中编写路由代码:
```javascript
const express = require('express');
const router = express.Router();
const { total } = require('./path/to/totalFunction');
router.get('/total', async (req, res) => {
const result = await total();
res.json(result);
});
module.exports = router;
这里使用 Express 的 Router 创建了一个新的路由,定义了一个 GET 请求的路由路径为 /total,然后在该路由的回调函数中调用 total() 函数,将其返回值作为 JSON 格式的响应返回给客户端。
-
引入路由:
在项目的入口文件(例如
app.js)中,引入并使用该路由:const express = require('express'); const apiRouter = require('./path/to/api'); const app = express(); app.use('/api', apiRouter); // ... 其他路由和中间件 app.listen(3000, () => { console.log('Server is listening on port 3000'); });这里使用
app.use()方法将/api路径下的所有请求交给apiRouter处理。
现在,启动服务器并访问 http://localhost:3000/api/total 即可获取网站总数的数据。
注意: ./path/to/totalFunction 应该替换为实际的 total 函数所在的文件路径。
通过以上步骤,我们成功创建了一个 API 路由,用于获取网站总数数据。您可以根据实际需要,对代码进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/mWVS 著作权归作者所有。请勿转载和采集!