前端使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM