vue怎么发送post请求
时间: 2023-09-25 19:15:29 浏览: 44
在 Vue 中发送 POST 请求可以使用 axios 库,可以按照以下步骤进行:
1. 安装 axios 库
可以使用 npm 或者 yarn 安装 axios:
```
npm install axios
```
或者
```
yarn add axios
```
2. 在 Vue 组件中使用 axios 发送 POST 请求
在需要发送 POST 请求的组件中引入 axios:
```javascript
import axios from 'axios'
```
然后在发送请求的方法中使用 axios.post() 方法:
```javascript
axios.post('/api/your-request-url', {
data: 'your data'
}).then(response => {
console.log(response)
}).catch(error => {
console.error(error)
})
```
其中第一个参数是请求的 URL,第二个参数是请求的数据。在 then() 方法中处理请求成功后的响应,在 catch() 方法中处理请求失败的情况。
注意:在发送 POST 请求时,需要设置请求头 Content-Type 为 application/json:
```javascript
axios.post('/api/your-request-url', {
data: 'your data'
}, {
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response)
}).catch(error => {
console.error(error)
})
```