我有一个应用程序,它使用react作为前端,使用nodejs/express作为后端。我的后端端点调用另一个 http 服务。在我的开发环境中,我想使用模拟数据而不是调用外部http服务。一个简短的例子:
app.get('/api/data', async (req, res) => {
try {
// Make an external API call
const response = await axios.get('https://someapi.com/do/1');
const data = response.data;
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch data from the external API' });
}
});
我不想从 api 获取数据,而是想从虚拟 json 获取数据。以下是执行此操作的方法:
使用 if/else 进行编码
app.get('/api/data', async (req, res) => {
try {
if(process.env.USE_MOCK ==true) {
res.json(return_mock_data_here)
}
else {
// Make an external API call
const response = await axios.get('https://someapi.com/do/1');
const data = response.data;
res.json(data);
}
} catch (error) {
res.status(500).json({ error: 'Failed to fetch data from the external API' });
}
});
使用模拟的快递服务器进行代码
app.get('/api/data', async (req, res) => {
try {
res.json(return_mock_data_here)
} catch (error) {
res.status(500).json({ error: 'Failed to fetch data from the external API' });
}
});
我不知道这样做更好的做法是什么。任何指示都会非常有帮助。
在这种情况下,我将完全存根
someapi
API。您需要对 Express 进行配置,以便您可以根据环境选择它与哪个 API 进行通信。然后,您需要有单独的运行配置,一个用于“正常”使用,另一个用于存根通信。