在JavaScript中调用网站接口通常是通过HTTP请求来实现的,这可以使用原生的XMLHttpRequest
对象或者更现代的fetch
API来完成。以下是一些基础概念和相关信息:
使用fetch
API发送GET请求:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There has been a problem with your fetch operation:', error));
使用fetch
API发送POST请求:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key1: 'value1', key2: 'value2' })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch((error) => console.error('Error:', error));
Content-Type
。.catch
块捕获错误信息,并据此进行调试。以上就是关于JavaScript调用网站接口的基础知识和常见问题解决方法。
领取专属 10元无门槛券
手把手带您无忧上云