JS接口请求的基本方法
使用fetch
进行GET请求:
fetch('https://api.example.com/data').then(response => response.json()).then(data => console.log(data)).catch(error => console.error('Error:', error));
使用fetch
进行POST请求:
fetch('https://api.example.com/data', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({key: 'value'}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用Axios库请求
安装Axios:
npm install axios
GET请求示例:
axios.get('https://api.example.com/data').then(response => console.log(response.data)).catch(error => console.error(error));
POST请求示例:
axios.post('https://api.example.com/data', {key: 'value'}).then(response => console.log(response.data)).catch(error => console.error(error));
处理异步请求
使用async/await
语法:
async function fetchData() {try {const response = await fetch('https://api.example.com/data');const data = await response.json();console.log(data);} catch (error) {console.error('Error:', error);}
}
fetchData();
设置请求头
添加自定义请求头:
fetch('https://api.example.com/data', {headers: {'Authorization': 'Bearer your_token','Custom-Header': 'value'}
});
处理跨域问题
服务器端设置CORS头:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type
开发环境代理配置(webpack):
devServer: {proxy: {'/api': {target: 'http://api.example.com',changeOrigin: true,pathRewrite: {'^/api': ''}}}
}
错误处理
检查HTTP状态码:
fetch('https://api.example.com/data').then(response => {if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return response.json();}).then(data => console.log(data)).catch(error => console.error('Error:', error));
取消请求
使用AbortController:
const controller = new AbortController();
const signal = controller.signal;fetch('https://api.example.com/data', {signal}).then(response => response.json()).then(data => console.log(data)).catch(error => {if (error.name === 'AbortError') {console.log('Request was aborted');}});// 取消请求
controller.abort();