Vue.js 中使用 PUT 请求 - Axios 库教程
在 Vue.js 中使用 PUT 请求可以通过 'axios' 库来实现。
首先需要在项目中安装 'axios' 库:
npm install axios
然后在需要使用 PUT 请求的组件中引入 'axios':
import axios from 'axios'
接下来,可以在组件中编写 PUT 请求的代码,例如:
axios.put('/api/user', {
name: 'John',
age: 28
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
在这个例子中,我们向 '/api/user' 发送一个 PUT 请求,请求的数据为 '{ name: 'John', age: 28 }'。请求成功后,会在控制台打印服务器返回的响应数据;请求失败时,会在控制台打印错误信息。
另外,需要注意的是,如果服务器需要在请求头中添加一些自定义的参数,可以使用 'headers' 属性。例如:
axios.put('/api/user', {
name: 'John',
age: 28
}, {
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
在这个例子中,我们在请求头中添加了 'Authorization' 和 'Content-Type' 两个参数。其中,'Authorization' 参数表示使用 Bearer Token 鉴权,'Content-Type' 参数表示请求的数据类型为 JSON。
原文地址: https://www.cveoy.top/t/topic/lFA3 著作权归作者所有。请勿转载和采集!