axios的post请求传参
-
使用
JSON.stringify()
将对象转换为JSON字符串作为请求体:axios.post('/api/data', JSON.stringify({ key: 'value' })) .then(response => console.log(response)) .catch(error => console.error(error));
-
如果你想要传递的数据是
FormData
,可以直接使用FormData
对象:const formData = new FormData(); formData.append('key', 'value'); axios.post('/api/data', formData) .then(response => console.log(response)) .catch(error => console.error(error));
-
如果你想要传递URL编码的数据,可以使用
URLSearchParams
对象:const params = new URLSearchParams(); params.append('key', 'value'); axios.post('/api/data', params) .then(response => console.log(response)) .catch(error => console.error(error));
-
如果你想要axios自动处理请求头,并发送JSON格式的数据,你可以直接传递一个JavaScript对象,并设置
Content-Type
为application/json
:axios.defaults.headers.post['Content-Type'] = 'application/json'; axios.post('/api/data', { key: 'value' }) .then(response => console.log(response)) .catch(error => console.error(error));