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

通用的一些流程
要判断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

posted @ 2022-03-06 10:39  叶常落  阅读(3178)  评论(0编辑  收藏  举报