在 vue.js 中,可以使用 $http.get() 和 $http.post() 方法发送 get 和 post 请求。$http.get() 方法用于发送 get 请求,$http.post() 方法用于发送 post 请求。响应通过 promise 对象返回,包含数据、状态码和响应头信息。

Vue.js 中的 GET 和 POST 请求
如何发送 GET 请求?
在 Vue.js 中发送 GET 请求,可以使用 $http.get() 方法:
<code class="javascript">this.$http.get('/endpoint').then(response => {
// 处理响应
});</code>其中,/endpoint 是要发送请求的 URL。
如何发送 POST 请求?
立即学习“前端免费学习笔记(深入)”;
发送 POST 请求,可以使用 $http.post() 方法:
<code class="javascript">this.$http.post('/endpoint', data).then(response => {
// 处理响应
});</code>其中,/endpoint 是要发送请求的 URL,data 是要发送的数据对象。
如何处理响应?
$http.get() 和 $http.post() 方法返回一个 Promise 对象,它解析后会返回一个响应对象。响应对象的结构如下:
<code>{
data: {}, // 服务器响应的数据
status: 200, // HTTP 状态码
headers: {} // 响应头信息
}</code>可以链式调用 then() 方法来处理响应:
<code class="javascript">this.$http.get('/endpoint').then(response => {
if (response.status === 200) {
// 处理数据
} else {
// 处理错误
}
});</code>其他选项
还有一些可选的参数可以用于自定义 GET 和 POST 请求:
-
timeout: 请求超时时间(以毫秒为单位) -
emulateJSON: 模拟 JSON 编码,以支持旧浏览器 -
headers: 请求头信息对象










