关于网络请求

ajax与XMLHttpRequest

前言

XMLHttpRequest是浏览器提供的一个对象,正是这个对象使得浏览器可以发出http请求、接收http响应。
ajax是一种技术方案,他最核心得依赖是XMLHttpRequest对象 只能说 使用XMLHttpRequest对象发送ajax请求。

get请求

var xhr = new XMLHttpRequest();
xhr.open('get',' url地址 ');//如果get请求需要传参 需要拼接在url后面
xhr.send(null); // get请求 参数不放在请求体 所以请求体为null
xhr.onreadystatechange=function(){
  if(xhr.readystate == 4){
      xhr.responseText //响应数据
  }
}

post请求

var xhr = new XMLHttpRequest();
xhr.open('post',' url地址 ');
xhr.send(请求体);
xhr.onreadystatechange=function(){
    .....
}

关于Content-Type

Content-Type是表明请求体数据类型
  get请求:
    因为get请求不放在请求体 故 get请求不需要设Content-Type

  post请求:
     不设置Content-Type 发送post请求,查看浏览器开发者工具 发现传参时候默认Content-Type 为                  text/plain;charset=UTF-8
     xhr发送post请求 默认Content-Type 为 text/plain;charset=UTF-8 表明纯文本
     
     如果发送的请求体为json格式 需要手动更改Content-Type
         xhr.setRequestHeader('Content-Type','application/json');
         xhr.send('{"name":"张三"}'); //注意json请求体 key 和 value 必须使用双括号包裹
     注意:Content-Type为application/json格式时,浏览器会先发送 OPTIONS 请求 
     目的是查看服务器是否支持该请求,如果不支持 则真正的请求不会发送成功
     常见问题 后台设置Access-Control-Allow-Headers没有添加content-type 会发送失败
         res.header("Access-Control-Allow-Headers", "X-Requested-With");
         (https://blog.csdn.net/qq_42396168/article/details/105547334)
     
     表单form 默认是get请求 改为post请求后 默认Content-Type为 application/x-www-form-urlencoded
     application-x-www.form-urlencoded表示表单请求 参数格式为 key1=value1&key2=value2
     如果不通过表单的action跳转请求、手动xhr发送请求 需要手动设置Content-Type为表单请求
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send('key1=v1&key2=v2');
     
     当需要上传文件类型时,表单form上传时 需要设置enctype="multipart/form-data" 表示上传的是formData对象
     不使用表单的action跳转请求、手动发送ajax请求时,需要手动设置Content-Type 为 multipart/form-data
     并且请求体内容为formData格式
        xhr.setRequestHeader('Content-Type','multipart/form-data');
        var formData = new FormData();
        formData.append('k','v');
        xhr.send(formData);

关于responseType

responseType 告诉浏览器将后台返回的数据以什么类型响应回来
如下载图片
var xhr = new XMLHttpRequest();
xhr.open('get',' url地址 ');
xhr.responseType='blob'
xhr.send();
xhr.onreadystatechange=function(){
     var blob =  xhr.response // 此时响应内容response即是blob类型
     //随后根据blob类型 生成下载链接 触发点击事件即可
     var url = URL.createObjectUrl(blob);
     var link = document.createElement('a');
     link.href=url;
     link.download='aa.jpg'; //download名字的后缀需要与blob类型一致 防止乱码
     link.click();//触发a链接的点击事件 实现下载
}

关于响应responseText/response

xhr不设置responseType时,响应内容会在xhr.responseText中
如果设置了响应类型responseType 响应内容会在response中
    xhr.responseTypr='blob';
    获取内容:  xhr.response
 全面获取响应内容的写法:
  const res = xhr.response?xhr.response:xhr.responseText
  res...

axios

前言

axios是一个基于promise的http网络请求库 也是vue.js2.0版本推荐使用的网络请求库

axios默认的一些配置

axios 默认Content-Type为 application/json;charset=UTF-8

get请求

axios.get(url).then().catch()
    axios.get(' url ').then(res=>{
        ...
    }).catch(err=>{
        ...
    })
axios.get(' url ',{ 配置参数 }).then().catch();
    axios.get(' url ',
            { 
                params: {name:'张三'},
                headers:{},
                responseType:'blob'
             }
             ).then(res=>{
                ...
             }).catch(err=>{
                ...
             })

post请求

axios.post(' url ').then().catch
    axios.post(' url ').then(res=>{
                            ...
                        }).catch(err=>{
                            ...
                        });
axios.post(' url ',{ 请求体数据 },{ 配置对象 }).then().catch()
    axios.post(' url ',
                 JOSN.stringify({name:'张三'}),
                 {
                    headers:{},
                    responseType:'blob'
                 }
              ).then(res=>{
                ...
              }).catch(err=>{
                ...
              });

axios封装

request.js:
  import axios from 'axios';
    export function(config){
        const instance=  axios.create({
              baseURL:‘’,
              timeout:‘’  
        })
        return instance;
    }

homeHttp.js:
    import {request} from './request.js
     export function getBanner(params){
              return request({
                              url:'',
                              method:‘get’
                  })
      }

相关对象

qs

qs是将对象序列化与反序列化的工具对象 
npm install qs --save
// 序列化
qs.stringify({ name:'zhangsan',age:20}) ----name=zhangsan&age=20
//反序列化
qs.parse('name=zhangsan&age=20) ---- {name:'zhangsan',age:20}

FormData

a、formData可以快速序列化一个form表单的数据 
  var fm = new FomrData('#form');
  fm.append(key,value);
  fm.get('name')
  ...
b、formData可实现图片二进制异步上传
    var fm = new FomrData();
    fm.append('key1','value1');
    fm.append('avatar',file)
    ...
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容