前端Axios-Day44
JSON Server:模拟服务器环境插件
1.进行全局安装:npm i -g json-server
2.创建db.json文件并写入相关数据:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
3.运行http://localhost:3000/posts或者http://localhost:3000/comments或者http://localhost:3000/profile即可得到数据。
Axios:前端Ajax请求库,基于Promise的HTTP客户端。
GET、POST、PUT、DELETE请求:
axios({
method:'请求类型',
url:'请求地址',
data:{value:"请求携带数据"},
}).then(response=> {
// Promise封装故配合then方法得到返回值(response/reject)
})
axios封装的方法:
axios.request():axios请求的别名
axios.request({
method: 'GET',
url: 'http://localhost:3000/comments',
}).then(response => console.log(response))
axios.post:axios的post请求别名(url,参数)
axios.post('http://localhost:3000/comments', {
"body": "some commentsss",
"postId": 2
}).then(response => console.log(response))
axios配置对象:config
① url:请求地址
② method:请求方式
③ baseUrl:请求基地址(相同部分)
④ transformRequest:对请求数据进行处理,处理后再发送至服务器。
⑤ transformResponse:对响应数据进行处理,处理后再传回客户端。
⑥ headers:对请求头信息进行配置。
⑦ params:对url进行设置动态参数。
⑧ responseType:表示服务器响应的数据类型。
Axios默认配置:defaults属性
eg:设置默认前缀url,默认请求方式等:
axios.defaults.method = 'GET'
axios.defaults.baseURL = 'http://localhost:3000'
Axios创建实例对象:create方法,用于设置对象的默认属性。
const ax1 = axios.create({
baseURL: " http://localhost:3000/posts",
timeout: 1000,
})
const ax2 = axios.create({
baseURL: "http://localhost:3000/comments",
timeout: 0,
})
ax1.get('/').then(response => console.log(response))
ax2.post('/', {
"body": "some commentsss",
"postId": 2,
}).then(response => console.log(response))

浙公网安备 33010602011771号