API对接平台一键对接
ChatGPT3.5/4.0,Claude3,文心一言
等AI模型,无需翻墙,国外信用卡👉AI模型聚合API-海鲸AI
在Node.js和Express中,可以通过中间件来统一API接口的返回格式。中间件可以拦截所有的响应并格式化它们,确保一致性。以下是一个简单的例子,展示了如何实现这样的中间件:
首先,你可以定义一个响应格式化的函数,例如:
function responseFormatter(req, res, next) {
// 保存原始的res.send
const originalSend = res.send;
// 重写res.send
res.send = function (data) {
// 格式化响应数据
let responseData = {
success: true,
data: data,
};
// 如果data是Error类型,则认为是失败的响应
if (data instanceof Error) {
responseData = {
success: false,
error: {
message: data.message,
...(process.env.NODE_ENV === 'development' && { stack: data.stack }), // 在开发环境下返回错误栈
},
};
}
// 调用原始的res.send方法
originalSend.call(this, responseData);
};
next();
}
然后,在你的Express应用中使用这个中间件:
const express = require('express');
const app = express();
// 使用responseFormatter中间件
app.use(responseFormatter);
// 定义路由
app.get('/api/some-endpoint', (req, res) => {
res.send({ message: 'This is a successful response!' });
});
app.get('/api/some-error', (req, res) => {
res.send(new Error('Something went wrong'));
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
在上面的例子中,responseFormatter
中间件会拦截所有通过res.send
发送的响应,并将其包装在一个统一的格式中。如果发送的是一个错误对象,它会改变响应的结构来表示失败的请求。
请注意,这只是一个基本的实现。在实际的应用中,你可能需要根据具体的业务逻辑来调整这个中间件的行为,例如处理不同类型的错误或者添加更多的响应信息。此外,对于错误处理,你可能还想要添加一个专门的错误处理中间件来捕获和格式化错误响应。