Axios+Ajax

axios:专注与数据请求的库

介绍

Axios,可以理解为ajax i/o system,这不是一种新技术,本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范。具备以下特点:

  1. 在浏览器中创建XMLHttpRequest请求

  2. 在node.js中发送http请求

  3. 支持Promise API

  4. 拦截请求和响应

  5. 转换请求和响应数据

  6. 取消要求

  7. 自动转换JSON数据

  8. 客户端支持防止CSRF/XSRF(跨域请求伪造)

原生XMLHttpRequest实现ajax请求

 var request = new XMLHttpRequest(); // 创建XMLHttpRequest对象
 ​
 // 发送请求:
 request.open('GET', '/api/categories');
 request.setRequestHeader("Content-Type", "application/json") //设置请求头
 request.send();//到这一步,请求才正式发出
 ​
 //ajax是异步的,设置回调函数
 request.onreadystatechange = function () { // 状态发生变化时,函数被回调
     if (request.readyState === 4) { // 成功完成
         // 判断响应状态码
         if (request.status === 200) {
             // 成功,通过responseText拿到响应的文本:
             return success(request.responseText);
         } else {
             // 失败,根据响应码判断失败原因:
             return fail(request.status);
         }
     } else {
         // HTTP请求还在继续...
     }
 }

axios是基于Promise的,因此可以使用Promise API

 axios的请求方式:
 axios(config)
 ​
 axios.request(config)
 ​
 axios.get(url [,config])
 axios.post(url [,data [,config]])
 axios.put(url [,data [,config]])
 axios.delete(url [,config])
 ​
 axios.patch(url [,data [,config]])
 ​
 axios.head(url [,config])
常用的请求:
//执行GET请求
import axios from 'axios'
axios.default.baseURL = 'http://localhost:3000/api/products'
axios.get('/user?ID=12345')  //返回的是一个Promise
    .then(res=>console.log(res))
    .catch(err=>console.log(err));

//可配置参数的方式
axios.get('/user',{
    params:{
        ID:12345
    		}
}).then(res=>console.log(res))
    .catch(err=>console.log(err));
    
    
    
//发送post请求
axios.post(
    '/user',
    {
    firstName: 'simon',
    lastName:'li'
	}).then(res=>{console.log(res)
        }).catch(err=>console.log(err));

调用axios方法得到的返回值是一个promise对象,

为什么我们所请求的数据在promise对象中?

因为当axios请求到数据后在外面给我们套了一层壳子,真正返回的数据在promise对象中的data中。

使用axios如何传参。

发送GET请求传参,使用params:{} 发送POST请求传参,使用data:{}

AXIOS基本使用

1、发起GET请求

2、发起POST请求

如果调用某个方法的返回值是一个promise实例,则可以直接在方法前面加上await

await只能使用在被async“修饰”的方法中

解构赋值:想要只得到某个对象中的某个属性值可以直接{属性名},重命名{属性名:‘新属性名’}

axios.get(url [,config])

axios.post(url [,data [,config]])

Ajax和fetch

ajax(){
 //前后端交互:application/json
 //json格式进行交互->json数据简单,直观,体积小
 let xhr = new XMLHttpRequest();
 xhr.open('POST',http://www.xxxxxx.xxxx/login);
 xhr.setRequestHeader('Content-Type','application/json');
 xhr.onreadystatechange = function(){
 if()
 }
 }

fetch:W3C开发的一个类似于XMLHttpRequest的一个函数,他封装了promise,也就是fetch中不用调用方法来接收数据,。Promise来接收数据。

注意

JavaScript中可以直接使用fetch()方法,在TS中要使用window.fetch()

axios--------later

制作的XMLHttpRequest从浏览器 让HTTP从node.js的请求 支持Promise API 拦截请求和响应 转换请求和响应数据 取消请求 JSON数据的自动转换 客户端支持防止XSRF

Request Config(可设置的请求属性)

 {
   // `url` is the server URL that will be used for the request
   
   url: '/user',
 ​
   // `method` is the request method to be used when making the request
   method: 'get', // default
 ​
   // `baseURL` will be prepended to `url` unless `url` is absolute.
   // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
   // to methods of that instance.
   //通用请求信息,会和url进行拼接
   baseURL: 'https://some-domain.com/api/',
 ​
   // `transformRequest` allows changes to the request data before it is sent to the server
   // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
   // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
   // FormData or Stream
   // You may modify the headers object.
   transformRequest: [function (data, headers) {
     // Do whatever you want to transform the data
 ​
     return data;
   }],
 ​
   // `transformResponse` allows changes to the response data to be made before
   // it is passed to then/catch
   transformResponse: [function (data) {
     // Do whatever you want to transform the data
 ​
     return data;
   }],
 ​
   // `headers` are custom headers to be sent
   //设置请求头
   headers: {'X-Requested-With': 'XMLHttpRequest'},
 ​
   // `params` are the URL parameters to be sent with the request
   // Must be a plain object or a URLSearchParams object
   //get请求参数,会自动将这里的添加到url请求中
   params: {
     ID: 12345
   },
 ​
   // `paramsSerializer` is an optional function in charge of serializing `params`
   // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
   paramsSerializer: function (params) {
     return Qs.stringify(params, {arrayFormat: 'brackets'})
   },
 ​
   // `data` is the data to be sent as the request body
   // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
   // When no `transformRequest` is set, must be of one of the following types:
   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
   // - Browser only: FormData, File, Blob
   // - Node only: Stream, Buffer
   //post请求参数
   data: {
     firstName: 'Fred'
   },
   
   // syntax alternative to send data into the body
   // method post
   // only the value is sent, not the key
   data: 'Country=Brasil&City=Belo Horizonte',
 ​
   // `timeout` specifies the number of milliseconds before the request times out.
   // If the request takes longer than `timeout`, the request will be aborted.
   //请求延时,当这个时间没有发起请求自动取消请求
   timeout: 1000, // default is `0` (no timeout)
 ​
   // `withCredentials` indicates whether or not cross-site Access-Control requests
   // should be made using credentials
   withCredentials: false, // default
 ​
   // `adapter` allows custom handling of requests which makes testing easier.
   // Return a promise and supply a valid response (see lib/adapters/README.md).
   adapter: function (config) {
     /* ... */
   },
 ​
   // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
   // This will set an `Authorization` header, overwriting any existing
   // `Authorization` custom headers you have set using `headers`.
   // Please note that only HTTP Basic auth is configurable through this parameter.
   // For Bearer tokens and such, use `Authorization` custom headers instead.
   auth: {
     username: 'janedoe',
     password: 's00pers3cret'
   },
 ​
   // `responseType` indicates the type of data that the server will respond with
   // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
   //   browser only: 'blob'
   responseType: 'json', // default
 ​
   // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
   // Note: Ignored for `responseType` of 'stream' or client-side requests
   responseEncoding: 'utf8', // default
 ​
   // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
   xsrfCookieName: 'XSRF-TOKEN', // default
 ​
   // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
   xsrfHeaderName: 'X-XSRF-TOKEN', // default
 ​
   // `onUploadProgress` allows handling of progress events for uploads
   // browser only
   onUploadProgress: function (progressEvent) {
     // Do whatever you want with the native progress event
   },
 ​
   // `onDownloadProgress` allows handling of progress events for downloads
   // browser only
   onDownloadProgress: function (progressEvent) {
     // Do whatever you want with the native progress event
   },
 ​
   // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
   maxContentLength: 2000,
 ​
   // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
   maxBodyLength: 2000,
 ​
   // `validateStatus` defines whether to resolve or reject the promise for a given
   // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
   // or `undefined`), the promise will be resolved; otherwise, the promise will be
   // rejected.
   validateStatus: function (status) {
     return status >= 200 && status < 300; // default
   },
 ​
   // `maxRedirects` defines the maximum number of redirects to follow in node.js.
   // If set to 0, no redirects will be followed.
   maxRedirects: 5, // default
 ​
   // `socketPath` defines a UNIX Socket to be used in node.js.
   // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
   // Only either `socketPath` or `proxy` can be specified.
   // If both are specified, `socketPath` is used.
   socketPath: null, // default
 ​
   // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
   // and https requests, respectively, in node.js. This allows options to be added like
   // `keepAlive` that are not enabled by default.
   httpAgent: new http.Agent({ keepAlive: true }),
   httpsAgent: new https.Agent({ keepAlive: true }),
 ​
   // `proxy` defines the hostname, port, and protocol of the proxy server.
   // You can also define your proxy using the conventional `http_proxy` and
   // `https_proxy` environment variables. If you are using environment variables
   // for your proxy configuration, you can also define a `no_proxy` environment
   // variable as a comma-separated list of domains that should not be proxied.
   // Use `false` to disable proxies, ignoring environment variables.
   // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
   // supplies credentials.
   // This will set an `Proxy-Authorization` header, overwriting any existing
   // `Proxy-Authorization` custom headers you have set using `headers`.
   // If the proxy server uses HTTPS, then you must set the protocol to `https`. 
   proxy: {
     protocol: 'https',
     host: '127.0.0.1',
     port: 9000,
     auth: {
       username: 'mikeymike',
       password: 'rapunz3l'
     }
   },
 ​
   // `cancelToken` specifies a cancel token that can be used to cancel the request
   // (see Cancellation section below for details)
   cancelToken: new CancelToken(function (cancel) {
   }),
 ​
   // an alternative way to cancel Axios requests using AbortController
   signal: new AbortController().signal,
 ​
   // `decompress` indicates whether or not the response body should be decompressed 
   // automatically. If set to `true` will also remove the 'content-encoding' header 
   // from the responses objects of all decompressed responses
   // - Node only (XHR cannot turn off decompression)
   decompress: true // default
 ​
   // `insecureHTTPParser` boolean.
   // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
   // This may allow interoperability with non-conformant HTTP implementations.
   // Using the insecure parser should be avoided.
   // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
   // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
   insecureHTTPParser: undefined // default
 ​
   // transitional options for backward compatibility that may be removed in the newer versions
   transitional: {
     // silent JSON parsing mode
     // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
     // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
     silentJSONParsing: true, // default value for the current Axios version
 ​
     // try to parse the response string as JSON even if `responseType` is not 'json'
     forcedJSONParsing: true,
     
     // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
     clarifyTimeoutError: false,
   }
 }

请求拦截器:interceptor

// Add a request interceptor
 //请求前拦截
 axios.interceptors.request.use(function (config) {
     // Do something before request is sent
     return config;
   }, function (error) {
     // Do something with request error
     return Promise.reject(error);
   });

响应拦截器

// Add a response interceptor
 axios.interceptors.response.use(function (response) {
     // Any status code that lie within the range of 2xx cause this function to trigger
     // Do something with response data
     return response;
   }, function (error) {
     // Any status codes that falls outside the range of 2xx cause this function to trigger
     // Do something with response error
     return Promise.reject(error);
   });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Axios、Vue和TypeScript的封装的Ajax请求示例: ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import { Vue } from 'vue-property-decorator'; // 定义全局配置 axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.timeout = 5000; // 定义请求拦截器 axios.interceptors.request.use((config: AxiosRequestConfig) => { // 在请求发送前做一些处理,例如添加token等 const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => { return Promise.reject(error); }); // 定义响应拦截器 axios.interceptors.response.use((response: AxiosResponse) => { // 在响应返回后做一些处理,例如判断是否登录失效等 const data = response.data; if (data.code === 401) { Vue.prototype.$message.error('登录失效,请重新登录!'); localStorage.removeItem('token'); location.href = '/login'; } return response; }, (error) => { return Promise.reject(error); }); // 定义请求方法 export const ajax = { get<T>(url: string, params?: any): Promise<T> { return axios.get(url, { params }).then((res: AxiosResponse) => res.data); }, post<T>(url: string, data?: any): Promise<T> { return axios.post(url, data).then((res: AxiosResponse) => res.data); }, put<T>(url: string, data?: any): Promise<T> { return axios.put(url, data).then((res: AxiosResponse) => res.data); }, delete<T>(url: string, params?: any): Promise<T> { return axios.delete(url, { params }).then((res: AxiosResponse) => res.data); } }; ``` 使用时可以直接引入`ajax`对象调用相应的请求方法: ```typescript import { ajax } from './ajax'; // 发送GET请求 ajax.get('/users', { page: 1, limit: 10 }).then((data) => { console.log(data); }).catch((error) => { console.error(error); }); // 发送POST请求 ajax.post('/users', { name: '张三', age: 18 }).then((data) => { console.log(data); }).catch((error) => { console.error(error); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值