vue中的axios的知识点梳理

230 阅读1分钟

axios知识点梳理

json-server搭建http服务

Get a full fake REST API with zero coding in less than 30 seconds (seriously)

有教你如何安装

github.com/typicode/js…

json-server的作用是axios可以向json-server发送请求,获取结果。

axios是什么

Promise based HTTP client for the browser and node.js

是基于Promise的HTTP客户端可以在浏览器和node.js两个环境中运行。

Features

  • Make XMLHttpRequests from the browser

    在浏览器中可以发送ajax请求

  • Make http requests from node.js

在服务器端可以发送http请求

支持promise的相关操作

  • Intercept request and response

在请求之前可以做一些准备工作和请求之后可以做一些预处理操作。

  • Transform request and response data

可以转换请求和相应数据

  • Cancel requests1

可以取消请求

  • Automatic transforms for JSON data

自动将结果转换位json数据

  • Client side support for protecting against XSRF

可以做保护防护跨站攻击。

如何安装

参考github.com/axios/axios 这个网站

项目中使用axios常用 npm install axiosyarn add axios 这两种方式

axios的使用

如何发送请求

get请求

axios({
//发送AJAX请求
method:'GET',
// URL
url:'http://localhost:3000/posts/2',

}).then(response =>{
console.log(response)
})

post请求

axios({
//发送AJAX请求
method:'POST',
// URL
url:'http://localhost:3000/posts/2',
//设置请求体
//把数据传给后台的json格式
data:{
title:'xxxxx',
author:'richkey'
}


}).then(response =>{
console.log(response)
})

put请求 (更新)

axios({
//发送AJAX请求
method:'PUT',
// URL
url:'http://localhost:3000/posts/3',
//设置请求体
//更新修改id为3中的数据内容
data:{
title:'dddd',
author:'richkey'
}


}).then(response =>{
console.log(response)
})

delete请求 删除

axios({
//发送AJAX请求
method:'delete',
// URL
//把id为3的数据删除
url:'http://localhost:3000/posts/3',

}).then(response =>{
console.log(response)
})