例子:
fetch('http://localhost:3000/api/data') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err));
例子:
当请求 http://localhost:3000/images/logo.png 时,确保logo.png文件已经放置在images文件夹下。
例子:
在服务端中定义路由:
app.get('/api/data', (req, res) => { const data = { name: 'John Doe', age: 30 }; res.json(data); });
在客户端代码中请求:
fetch('http://localhost:3000/api/data') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err));
在以上例子中,当请求http://localhost:3000/api/data时,服务端会响应一个JSON对象{name: 'John Doe', age: 30}。客户端代码通过fetch函数请求该URL,并把响应的数据输出到控制台上。