API的获取可以放在前端或后端,具体取决于项目的需求和架构。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.get('/data', (req, res) => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// 处理返回的数据
res.json(data);
})
.catch(error => {
// 处理错误
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
上述代码创建了一个使用Express框架的简单服务器,并在/data
路由中获取API数据。服务器会在3000端口上监听请求,并将获取的数据返回给客户端。
总结: