前端使用js发起http请求的几种方法

本文深入探讨了HTTP请求的各种方法,包括fetch, axios, ajax, XMLHttpRequest和request的使用方式及示例代码。通过本文,读者可以了解如何处理HTTP响应,解析JSON数据,并掌握不同场景下选择合适请求方法的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通用的一些流程
要判断http返回码
要判断body里面业务返回码
是否能够跨域
是否能够携带Cookie

常用的方法有fetch, ajax, axios, XMLHttpRequest,request,下面有具体介绍
在这里插入图片描述

  1. fetch
    https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
    // Your code for handling the data you get from the API
})
.catch(function() {
    // This is where you run code if the server returns any errors
});
  1. axios
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  1. ajax
 $.ajax({
             type: "GET",
             url: "test.json",
             data: {username:$("#username").val(), content:$("#content").val()},
             dataType: "json",
             success: function(data){
                       console.log(data)
                      }
         });
  1. XMLHttpRequest
    细节使用 https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open('GET', '/url', true);
xhr.send();
  1. request
const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

一种比较可行的方案是在utils里面把请求处理到json层次,然后业务层次只要判读json里面的业务码就好了。
因为一个项目,origin固定,path传参数,post方法可以固定,header头可以可固定,body传参数

问题:
Cross-Origin Read Blocking (CORB) blocked cross-origin response

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值