前言:
目前你们对“浏览器ajax请求拦截器怎么关闭”大体比较看重,咱们都想要了解一些“浏览器ajax请求拦截器怎么关闭”的相关资讯。那么小编在网摘上网罗了一些关于“浏览器ajax请求拦截器怎么关闭””的相关知识,希望兄弟们能喜欢,各位老铁们一起来学习一下吧!安装
$ npm install axioscdn 国内
<script src=";></script>
<script src=";></script> 国外简单案例 Get
//获取用户axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed});
上面代码另一种写法
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed});use async/await
async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); }}let user = getUser();执行POST请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error);});执行多个并发请求
function getUserAccount() { return axios.get('/user/12345');}function getUserPermissions() { return axios.get('/user/12345/permissions');}Promise.all([getUserAccount(), getUserPermissions()]) .then(function (results) { const acct = results[0]; const perm = results[1];});通过将相关配置来发出请求axios
axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' }});请求方法别名
所有常见的请求方法提供了别名
axios.request(config)axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.options(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])
别名样例
axios.request({ method:'GET', url: ';}).then(response => { console.log(response);})
axios.post( ';, { "body": "喜大普奔", "postId": 2 }).then(response => { console.log(response);})请求配置
这些是用于发出请求的可用配置选项。仅url是必需的。GET如果method未指定,请求将默认为。
{ // `url`是将用于请求的服务器URL url: '/user', // `method`是发出请求时使用的请求方法 method: 'get', // 默认 // `baseURL`将被添加到`url`前面,除非`url`是绝对的。 // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。 baseURL: ';, // `transformRequest`允许在请求数据发送到服务器之前对其进行更改 // 这只适用于请求方法'PUT','POST'和'PATCH' // 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream transformRequest: [function (data, headers) { //做任何你想要的数据转换 return data; }], //`transformResponse`允许在 then / catch之前对响应数据进行更改 transformResponse: [function (data) { // 执行任何要转换数据的操作 return data; }], // `headers`是要发送的自定义 headers headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params`是要与请求一起发送的URL参数 // 必须是纯对象或URLSearchParams对象 params: { ID: 12345 }, // `paramsSerializer`是一个可选的函数,负责序列化`params` paramsSerializer: { indexes: null // array indexes format (null - no brackets, false - empty brackets, true - brackets with indexes) }, // `data`是要作为请求主体发送的数据 // 仅适用于请求方法“PUT”,“POST”和“PATCH” //当没有设置`transformRequest`时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // 将数据发送到正文的语法替代方案 // method post //只发送value,不发送key data: 'Country=Brasil&City=Belo Horizonte', // `timeout`指定请求超时之前的毫秒数。 // 如果请求的时间超过'timeout',请求将被中止。 timeout: 1000, // default is `0` (no timeout) // `withCredentials`指示是否跨站点访问控制请求 ,是否带上Cookie // should be made using credentials withCredentials: false, // default // `adapter'允许自定义处理请求,这使得测试更容易。 // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth'表示应该使用 HTTP 基本认证,并提供凭据。 // 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。 auth: { username: 'janedoe', password: 's00pers3cret' }, // “responseType”表示服务器将响应的数据类型 // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `responseEncoding` 表示服务器将响应的数据编码 (Node.js only) // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName`是携带xsrf令牌值的http头的名称 xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress`允许处理上传的进度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress`允许处理下载的进度事件 onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength`定义允许的http响应内容的最大大小 maxContentLength: 2000, // `maxBodyLength` (Node only option) 定义允许的http请求内容的最大大小(以字节为单位) maxBodyLength: 2000, // `validateStatus` 定义是否解析或拒绝给定的promise // 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`定义在node.js中要遵循的重定向的最大数量。 // 如果设置为0,则不会遵循重定向。 maxRedirects: 21, // default // `beforeRedirect` defines a function that will be called before redirect. // Use this to adjust the request options upon redirecting, // to inspect the latest response headers, // or to cancel the request by throwing an error // If maxRedirects is set to 0, `beforeRedirect` is not used. beforeRedirect: (options, { headers }) => { if (options.hostname === "example.com") { options.auth = "user:password"; } }, // `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”指定可用于取消请求的取消令牌 // (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 // see also 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, }, env: { // The FormData class to be used to automatically serialize the payload into a FormData object FormData: window?.FormData || global?.FormData }, formSerializer: { visitor: (value, key, path, helpers)=> {}; // custom visitor funaction to serrialize form values dots: boolean; // use dots instead of brackets format metaTokens: boolean; // keep special endings like {} in parameter key indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes }}响应模式
请求的响应包含以下信息。
{ // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lowercase and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {}}
使用时then,您将收到如下响应:
axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config);});配置默认值
您可以指定将应用于每个请求的配置默认值。
全局 axios 默认值
axios.defaults.baseURL = ';;// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.// See below for an example using Custom instance defaults instead.axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.common['Authorization'] = "Bearer " + access_token; //Jwtaxios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';自定义实例默认值
// Set config defaults when creating the instanceconst instance = axios.create({ baseURL: ';});// Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization'] = AUTH_TOKEN;配置优先顺序
axios.defaults.config < instance.config < request.config
// Create an instance using the config defaults provided by the library// At this point the timeout config value is `0` as is the default for the libraryconst instance = axios.create();// Override timeout default for the library// Now all requests using this instance will wait 2.5 seconds before timing outinstance.defaults.timeout = 2500;// Override timeout for this request as it's known to take a long timeinstance.get('/longRequest', { timeout: 5000});拦截器
// Add a request interceptoraxios.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 interceptoraxios.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);});可以将拦截器添加到 axios 的自定义实例中。
const instance = axios.create();instance.interceptors.request.use(function () {/*...*/});还可以清除请求或响应的所有拦截器。
const instance = axios.create();instance.interceptors.request.use(function () {/*...*/});instance.interceptors.request.clear(); // Removes interceptors from requestsinstance.interceptors.response.use(function () {/*...*/});instance.interceptors.response.clear(); // Removes interceptors from responses
请求拦截器时,默认情况下被认为是异步执行的。当主线程被阻塞时,这可能会导致 axios 请求的执行延迟。如果您的请求拦截器是同步的,您可以向选项对象添加一个标志,该标志将告诉 axios 同步运行代码并避免请求执行中的任何延迟。
axios.interceptors.request.use(function (config) { config.headers.test = 'I am only a header!'; return config;}, null, { synchronous: true });
如果要根据运行时检查执行特定拦截器,可以runWhen向选项对象添加一个函数。当且仅当返回的runWhen是时,拦截器不会被执行false。该函数将使用配置对象调用(不要忘记您也可以将自己的参数绑定到它)。当您有一个只需要在特定时间运行的异步请求拦截器时,这会很方便。
function onGetCall(config) { return config.method === 'get';}axios.interceptors.request.use(function (config) { config.headers.test = 'special get headers'; return config;}, null, { runWhen: onGetCall });处理错误
axios.get('/user/12345') .catch(function (error) { if (error.response) { // 请求已发出,服务器以状态代码响应 //超出2xx的范围 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // 已发出请求,但未收到响应 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // 设置请求时发生了触发错误的问题 console.log('Error', error.message); } console.log(error.config); });
使用validateStatusconfig 选项,您可以定义应引发错误的 HTTP 代码。
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // 仅当状态代码小于500时解决 }})
使用toJSON您可以获得一个包含有关 HTTP 错误的更多信息的对象。
axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON());});取消
通过将执行器函数传递给构造函数来创建取消标记CancelToken:
const CancelToken = axios.CancelToken;let cancel;axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; })});// cancel the requestcancel();
有个很好的场景,如果在抢购的时候,用户疯狂的抢购按钮,但是服务器每次响应至少需要2-3秒。那么就会疯狂的发请求,加重服务器的负担。这个时候取消就很有用了。用户可以疯狂的点,但我们可以取消啊。看代码案例
//获取按钮const btns = document.querySelectorAll('button');//2.声明全局变量let cancel = null;//发送请求btns[0].onclick = function(){ //检测上一次的请求是否已经完成 if(cancel !== null){ //取消上一次的请求 cancel(); } axios({ method: 'GET', url: ';, //1. 添加配置对象的属性 cancelToken: new axios.CancelToken(function(c){ //3. 将 c 的值赋值给 cancel cancel = c; }) }).then(response => { console.log(response); //将 cancel 的值初始化 cancel = null; }) }使用application/x-www-form-urlencoded格式URL搜索参数
默认情况下,axios 将 JavaScript 对象序列化为JSON. application/x-www-form-urlencoded要以该格式发送数据,您可以使用绝大多数浏览器都支持的URLSearchParamsAPI
const params = new URLSearchParams({ foo: 'bar' });params.append('extraparam', 'value');axios.post('/foo', params);查询字符串
或者以另一种方式(ES6),
import qs from 'qs';const data = { 'bar': 123 };const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url,};axios(options);自动序列化为 URLSearchParams
如果 content-type-header 设置为“application/x-www-form-urlencoded”,Axios 会自动将数据对象序列化为 urlencoded 格式。
const data = { x: 1, arr: [1, 2, 3], arr2: [1, [2], 3], users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],};await axios.postForm(';, data, {headers: {'content-type': 'application/x-www-form-urlencoded'}});
服务器将把它处理为
{ x: '1', 'arr[]': [ '1', '2', '3' ], 'arr2[0]': '1', 'arr2[1][0]': '2', 'arr2[2]': '3', 'users[0][name]': 'Peter', 'users[0][surname]': 'griffin', 'users[1][name]': 'Thomas', 'users[1][surname]': 'Anderson' }使用multipart/form-data格式表单数据
要将数据发送,multipart/formdata您需要传递一个 formData 实例作为有效负载。Content-Type不需要设置标头,因为 Axios 根据有效负载类型猜测它。
const formData = new FormData();formData.append('foo', 'bar');axios.post(';, formData);自动序列化为 FormData
从 开始v0.27.0,如果请求Content-Type 标头设置为,Axios 支持自动对象序列化为 FormData 对象multipart/form-data。
以下请求将以 FormData 格式提交数据
import axios from 'axios';axios.post(';, {x: 1}, { headers: { 'Content-Type': 'multipart/form-data' }}).then(({data})=> console.log(data));
假设我们有一个像这样的对象:
const obj = { x: 1, arr: [1, 2, 3], arr2: [1, [2], 3], users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], 'obj2{}': [{x:1}]};
以下步骤将由 Axios 序列化器内部执行:
const formData= new FormData();formData.append('x', '1');formData.append('arr[]', '1');formData.append('arr[]', '2');formData.append('arr[]', '3');formData.append('arr2[0]', '1');formData.append('arr2[1][0]', '2');formData.append('arr2[2]', '3');formData.append('users[0][name]', 'Peter');formData.append('users[0][surname]', 'Griffin');formData.append('users[1][name]', 'Thomas');formData.append('users[1][surname]', 'Anderson');formData.append('obj2{}', '[{"x":1}]');
axios 支持以下快捷方法:postForm、putForm,patchForm 这只是对应的 http 方法,头Content-Type预设为multipart/form-data。
上传文件
单个文件
await axios.postForm(';, { 'myVar' : 'foo', 'file': document.querySelector('#fileInput').files[0] });
多个文件作为multipart/form-data.
await axios.postForm(';, { 'files[]': document.querySelector('#fileInput').files });
FileList可以直接传递对象
await axios.postForm(';, document.querySelector('#fileInput').files)
所有文件都将使用相同的字段名称发送:files[]
HTML 表单提交
将 HTML Form 元素作为有效负载传递,以将其作为multipart/form-data内容提交。
await axios.postForm(';, document.querySelector('#htmlForm'));
FormData并且对象也可以通过将headers 显式设置为来HTMLForm提交:JSON Content-Type application/json
await axios.post(';, document.querySelector('#htmlForm'), { headers: { 'Content-Type': 'application/json' //告诉服务端是json方式提交的 }})
例如,表格
<form id="form"> <input type="text" name="foo" value="1"> <input type="text" name="deep.prop" value="2"> <input type="text" name="deep prop spaced" value="3"> <input type="text" name="baz" value="4"> <input type="text" name="baz" value="5"> <select name="user.age"> <option value="value1">Value 1</option> <option value="value2" selected>Value 2</option> <option value="value3">Value 3</option> </select> <input type="submit" value="Save"></form>
将作为以下 JSON 对象提交:
{ "foo": "1", "deep": { "prop": { "spaced": "3" } }, "baz": [ "4", "5" ], "user": { "age": "value2" }}