js使用fetch get接口例子
以下是一个使用Fetch API进行GET请求的例子:
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
在这个例子中,我们使用fetch()方法来发送一个GET请求到https://example.com/api/data接口。一旦收到响应,我们使用.json()方法将响应体解析为JSON格式。然后我们使用.then()方法处理解析后的数据并将其输出到控制台。如果发生错误,我们使用.catch()方法捕获它并输出到控制台。
请注意,如果您需要指定其他选项(例如HTTP标头或请求方法),您可以在fetch()方法中传递一个选项对象。例如,下面是一个使用POST方法发送JSON数据的示例:
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'example', password: '1234' })
};
fetch('https://example.com/api/login', requestOptions)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
原文地址: http://www.cveoy.top/t/topic/ZP2 著作权归作者所有。请勿转载和采集!