网络请求操作

0 阅读2分钟

1.原生AJAX

1.1 get请求

// 1. 原生ajax
// 1.1 get请求
// 原生ajax通过XMLHttpRequest()进行生成的
const xhr=new XMLHttpRequest();
// 使用open方法开启请求
// get方法可以带参数,参数会拼接在url后面,使用&连接
xhr.open('get','http://127.0.0.1:3000/get?name=chensq&age=18');
// 使用send方法发送请求
xhr.send();
// 使用onreadystatechang事件来接收服务器的响应
xhr.onreadystatechange=function(){
  // 如果为4(或者XMLHttpRequest.DONE),则表示完成
  if(xhr.readyState===4&&xhr.status===200){
    // 使用JSON.parse()方法将响应数据转为JSON对象
      console.log(JSON.parse(xhr.responseText))
  }
}

控制台输出
image.png

1.2 post请求

// 1. 原生ajax
// 1.2 post请求
// 原生ajax通过XMLHttpRequest()进行生成的
const xhr=new XMLHttpRequest();
// 使用open方法开启请求
// get方法可以带参数,参数会拼接在url后面,使用&连接
xhr.open('post','http://127.0.0.1:3000/post');
// 设置请求头:告诉请求参数的相关信息
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 使用send方法发送请求 注意:post参数在send中,而不是拼接在url后面
xhr.send('name=chensuipian&age=18');
// 使用onreadystatechang事件来接收服务器的响应
xhr.onreadystatechange=function(){
  // 如果为4(或者XMLHttpRequest.DONE),则表示完成
  if(xhr.readyState===4&&xhr.status===200){
    // 使用JSON.parse()方法将响应数据转为JSON对象
      console.log(JSON.parse(xhr.responseText))
  }
}

控制台输出

image.png

2 Axios--主流发送库

2.1 get

2.1.1 在url拼接参数

// 2. axios
// axios是一个对象也是一个函数
(async()=>{
const res=  await axios.get('http://127.0.0.1:3000/get?name=tom&age=18')
console.log(res.data);
})()

结果:

image.png

2.1.2 将params作为第二个参数

// 2. axios
// axios是一个对象也是一个函数
(async()=>{
const res=  await axios.get('http://127.0.0.1:3000/get',{
  params:{
    name:'张三',
    age:18
  }
})
console.log(res.data);
})()

实现结果与2.1.1相同

image.png

2.2 post


// 2. axios
// axios是一个对象也是一个函数
(async()=>{
const res=  await axios.post('http://127.0.0.1:3000/post',{
// 注意:post不能拼接在URL后面,只能放在请求体中,且不用套在params中
    name:'张三',
    age:18
})
console.log(res.data);
})()

结果:

image.png

2.3 axios提供的更加便利的功能

使用axios.create方法进行自定义的配置选项

// 2. axios
// axios是一个对象也是一个函数
(async()=>{
 const init= axios.create({
    baseURL:'http://127.0.0.1:3000',
    timeout:5000
  })
// 2.1 拦截器
  // 请求拦截器:只要配置了拦截器,那么请求就会经过拦截器处理
  init.interceptors.request.use(config=>{ // 请求拦截器处理逻辑
    console.log('请求拦截器处理逻辑')
    return config
})
  // 响应拦截器:只要配置了拦截器,那么响应就会经过拦截器处理
  init.interceptors.response.use(res=>{
    return res.data
  })
const res=  await axios.post('http://127.0.0.1:3000/post',{
// 注意:post不能拼接在URL后面,只能放在请求体中,且不用套在params中
    name:'张三',
    age:18
})
console.log(res.data);
})()

3 Fetch API

3.1 get

// 3. fetch
// 3.1 get
fetch('http://127.0.0.1:3000/get?name=张三&age=18').then(res=>{
  if(res.ok) {
    return res.json()
  }
})
.then(data=>{
  console.log(data)
})

结果:

image.png

3.2 post

// 3. fetch
// 3.1 post
fetch('http://127.0.0.1:3000/post',{
  method:'POST',
  headers:{
    'Content-Type':'application/json'
  },
  // 将js对象转为json字符串
  body:JSON.stringify({
    name:'chensuipian',
    age:18
  })
}).then(res=>{
  if(res.ok) {
    return res.json()
  }
})
.then(data=>{
  console.log(data)
})

结果:

image.png