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

4,159 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

本文介绍前端使用js发送http/https请求的几种方法: 我最新欢fetch方法,因为在类chrome浏览器中,可以copy as fetch,再也不用手工敲格式化的代码了。 注意:下面的任何代几乎都是伪代码,不要直接用。

通用的一些流程

要判断http返回码

要判断body里面业务返回码

是否能够跨域

是否能够携带Cookie

常用的方法有fetch, ajax, axios, XMLHttpRequest,request,下面有具体介绍

image.png

  1. fetch scotch.io/tutorials/h…
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 细节使用 developer.mozilla.org/zh-CN/docs/…
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