• Web:前端常用的几种Http请求GET和POST样例


    1、简述

    在Web开发过程中,少不了发起Http请求服务端的接口数据,在不同的框架中使用了不同的Http请求方式,常用的请求有fetch、 ajax、 axios、XMLHttpRequest、request,以下样例仅供参考。
    在这里插入图片描述

    2、Fetch

    Fetch API 是一种 JavaScript API,是一种基于 Promise 的现代API,用于在网络中发送和接收请求。具有一下特点:

    • 更简洁的 API:只需要一个函数就可以完成网络请求。
    • 基于 Promise:支持更直观的异步编程。
    • 内置 Request 和 Response 类:方便进行请求和响应的处理。
    • 支持跨域请求:允许在不同域名之间进行数据交互。
    2.1 GET
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => {
        console.log(data); // 处理返回的数据
      })
      .catch(error => {
        console.error(error); // 处理错误
      });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    2.2 POST
    const data = new FormData();
    data.append('name', '张');
    data.append('age', 20);
    fetch('https://example.com/submit', {
    method: 'POST',
    headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'
    }),
    body: new URLSearchParams(data)
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3、Ajax

    Ajax 全称“Asynchronous JavaScript and XML”,译为“异步 JavaScript 和 XML”,程序员们习惯称之为“阿贾克斯”,它并不是一种技术,而是多种技术的综合体,其中包括 JavaScript、XML、JSON、DOM、CSS、HTML 以及最重要的 XMLHttpRequest 对象。通过 Ajax 可以异步从服务器请求数据并将数据更新到网页中,整个过程不需要重载(刷新)整个网页,可以将网页的内容更快的呈现给用户。

    3.1 GET
    $.ajax({
    	url: "https://api.example.com/data",
    	type: 'GET',
    	dataType: 'json',
    	success: function (data) {
    	},
    	error: function () { 
    	}
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    3.2 POST
    let formData = new FormData();
    formData.append('id', fileId);
    $.ajax({
    	url:'https://example.com/submit',
    	type: 'POST',
    	processData: false,
    	contentType: false,
    	data: formData,
    	dataType: 'json',
    	success: function (data) {
    	},
    	error: function (e) {
    	}
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    3.3 Done

    从JQuery 1.8,$.ajax()的 success() 被替换为 done() ,error() 被替换为 fail() ,complete() 被替换为 always() 。

    $.ajax({
    		type: "POST",
    		url: "https://example.com/submit",
    		dataType: "json",
    	}).done(function(data){                         
    		console.log(data)
    	}).fail(function(jqXHR, textStatus, errorThrown){
    		
    	}).always(function( jqXHR, textStatus ){
    		
    	});	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4、Axios

    Axios是一个基于promise的HTTP库,类似于jQuery的ajax,用于http请求。可以应用于浏览器端和node.js,既可以用于客户端,也可以用于node.js编写的服务端。

    • 支持Promise API
    • 拦截请求与响应,比如:在请求前添加授权和响应前做一些事情。
    • 转换请求数据和响应数据,比如:进行请求加密或者响应数据加密。
    • 取消请求
    • 自动转换JSON数据
    • 客户端支持防御XSRF
    4.1 引用

    常用的引入axios方法:

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 
    
    • 1

    或者通过node npm来安装:

    npm install axios
    
    • 1

    方法列举:GET、POST、PUT、PATCH、DELETE

    4.2 GET
    let params= {};
    params.id = 1;
    axios({
        method: "GET",
        url: "https://api.example.com/data",
        params:params
      }).then(res => {
        console.log(res);
      });
      
    或者
    
    axios.get("https://api.example.com/data", {
           params: params
         })
         .then(res => {
           console.log(res);
         })
         .catch(err => {
           console.log(err);
         });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    4.3 POST
    let formData = new FormData();
    formData.append('id', fileId);
    axios.post('https://example.com/submit',formData).then(res=>{
      console.log(res,'formData')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5、XMLHttpRequest

    XMLHTTPRequest对象,顾名思义:是基于XML的HTTP请求。XMLHTTPRequest是一个浏览器接口,使得Javascript可以进行HTTP(S)通信。XMLHTTPRequest(XHR)对象用于与服务器交互,我们通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL获取数据,并且虽然名字叫XMLHTTPRequest,但实际上可以用于获取任何类型的数据。

    5.1 GET
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.example.com/data');
    xhr.send(); 
    xhr.onreadystatechange = function(){
        if ( xhr.readyState == 4 && xhr.status == 200 ) {
          alert( xhr.responseText );
        } else {
          alert( xhr.statusText );
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    5.2 POST
    var xhr = new XMLHttpRequest();
    xhr.open('post', 'https://example.com/submit', true);
    xhr.responseType = "blob";
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    xhr.onload = function () {
    	if (xhr.status == 200) {
    		var blob = new Blob([xhr.response], {
    			type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; application/octet-stream;charset=utf-8"'
    		})
    		var reader = new FileReader();
    		reader.onload = function () {
    			console.log(this.result);
    		};
    		reader.readAsArrayBuffer(blob);
    	}
    };
    xhr.send();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    6、Request

    Node.js是一个基于Chrome V8 JavaScript引擎的开源、跨平台的Javascript运行环境,使JavaScript可以脱离浏览器运行。它提供了很多强大的模块,使Web开发更轻松。其中,request模块是一个使用最广泛的HTTP模块,可以用来发送HTTP/HTTPS请求。

    添加request模块:

    npm install request
    
    • 1
    6.1 GET
    var request = require('request');
    request.get('https://api.example.com/data', function(error, response, body) {
      console.log(body);
    });
    
    • 1
    • 2
    • 3
    • 4
    6.2 POST
    var request = require('request');
    request.post('https://example.com/submit', {form:{key:'value'}}, function(error, response, body) {
      //上传文件或者其他操作
    });
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    PHP 初学 GO 学习笔记
    第二章STP应用配置
    SpringBoot整合Swagger3和Knife4j及使用
    相机内参及其内参影响因素的几点思考
    基于Matlab使用地面雷达探测和跟踪LEO卫星星座仿真(附源码)
    Pyecharts绘图教程(2)—— 绘制多种折线图(Line)参数说明+代码实战
    [Pandas技巧] 分组比例计算求和
    OCR表格识别—(一)
    从一次性销售到持续收益:低代码服务商的转型之路
    zookeeper集群安装
  • 原文地址:https://blog.csdn.net/lishangke/article/details/133384530