In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "how to use vue's axios". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use vue's axios" can help you solve your doubts.
In vue, axios is a promise-based HTTP library that is mainly used to implement AJAX asynchronous communication functions; axios can send XMLHttpRequests requests in browsers, send http requests in nodejs, and intercept request and response, translation request and response data.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
Axios: front-end communication framework, because the boundary of vue is very clear, it is to deal with DOM, so there is no communication function, so you need to use an additional communication framework to interact with the server; of course, you can also use the AJAX communication function provided by jQuery.
Axios is a promise-based HTTP library, which can simply send get and post requests.
When it comes to get and post, the first thing we should think of is Jquery. After all, when Jquery was more popular a few years ago, everyone was using it. However, due to the emergence of Vue, React and other frameworks, Jquery is not so popular. It is the emergence of Vue, React and other frameworks that promote the emergence of Axios lightweight libraries, because Vue and other, do not need to operate Dom, so there is no need to introduce Jquery.js.
Axios characteristics
1. You can send XMLHttpRequests in the browser.
2. You can send http requests in node.js.
3. Support Promise API
4. Intercept requests and responses
5. Convert request data and response data
6. Can cancel the request
7. Automatically convert JSON data
8. The client supports protecting security from XSRF attacks.
What are the scenarios where Axios is used?
It has been mentioned in the feature that Axios can be used by browsers to send requests or Node.js to send requests. Projects such as Vue, React, Node and so on can use Axios. If you use Jquery in your project, you don't need to bother at this time. You can send requests in jquery itself.
How do I use Axios?
Installation module
Npm install axios
Or directly introduce
After introducing the module, you can use it directly.
Example (1)
/ / GETaxios.get ('/ user', {params: {ID: 12345}}) .then (function (response) {console.log (response);}) .catch (function (error) {console.log (error);}); / / POSTaxios.post ('/ user', {name: 'Javan', website:' www.javanx.cn'}). Then (function (response) {console.log (response) ) .catch (function (error) {console.log (error);})
The above parameters are optional
If you want to concurrently multiple requests, you can look at the code below
Function getUserAccount () {return axios.get ('/ user/12345');} function getUserPermissions () {return axios.get ('/ user/12345/permissions');} axios.all ([getUserAccount (), getUserPermissions ()]) .then (axios.spread (function (acct, perms) {/ / both requests are executed}))
Example (2)
In addition to the above, you can create a request by passing the relevant configuration to axios, such as:
/ / POSTaxios ({method: 'post', url:' / user/12345', data: {firstName: 'Fred', lastName:' Flintstone'}})
Grammar
Axios (url [, config])
Config
{/ / `url` is the server URL url for the request:'/ user', / / `method` is the method method used when creating the request: 'get', / / default is get / / `baseURL` will be automatically added before `url`, unless `url` is an absolute URL. / / it can easily pass the relative URL baseURL for the method of axios instance by setting a `baseURL`: 'https://some-domain.com/api/', / / `transformRequest` allows you to modify the request data / / which can only be used in the' PUT', 'POST' and' PATCH' 'request methods / / the functions in the subsequent array must return a string or ArrayBuffer before sending to the server. Or Stream transformRequest: [function (data) {/ / A return data for arbitrary conversion of data }], / / `transformResponse` allows you to modify the response data transformResponse before passing it to then/catch: [function (data) {/ / a pair of data for arbitrary conversion processing return data }], / / `headers` is the custom request header headers to be sent: {'XmurRequestedmurWithparts:' XMLHttpRequest'}, / / `params` is the URL parameter to be sent with the request / / must be an unformatted object (plain object) or URLSearchParams object params: {ID: 12345}, / / `paramsSerializer` is a function responsible for `params` serialization / (e.g. Params`. Http://api.jquery.com/jquery.param/) paramsSerializer: function (params) {return Qs.stringify (params, {arrayFormat: 'brackets'})}, / / `data` is the data sent as the body of the request / / only applies to these request methods' PUT', 'POST', and' PATCH' / / when `transformRequest` is not set Must be one of the following types: / /-string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams / /-browser specific: FormData, File, Blob / /-Node exclusive: Stream data: {firstName: 'Fred'}, / / `timeout` specifies the number of milliseconds of request timeout (0 means no timeout) / / if the request charges more than `timeout` The request will be interrupted timeout: 1000. / / `withCredentials` indicates whether you need to use the credential withCredentials: false for cross-domain requests. / / default / / `adapter` allows custom processing of requests to make it easier to test / / return a promise and apply a valid response (see [response docs] (# response-api)). Adapter: function (config) {/ *... * /}, / / `auth` indicates that HTTP basic authentication should be used and provides credentials / / this will set a `Authorization` header to overwrite any existing custom `Authorization` header set using `headers`: {username: 'janedoe', password:' s00pers3cret`}, / / `responseType` indicates the data type of server response It can be 'arraybuffer',' blob', 'document',' json', 'text',' stream' responseType: 'json', / / default / / `xsrfCookieName` is the name of the cookie used as the value of xsrf token: xsrfCookieName:' XSRF-TOKEN', / / default / / `xsrfHeaderName` is the name of the HTTP header that carries the value of xsrf token: xsrfHeaderName: 'XmurXSRF / / default / / `onUploadProgress` allows processing of progress events onUploadProgress: function (progressEvent) {/ / a pair of native progress events} for upload, / / `onDownloadProgress` allows processing of progress events onDownloadProgress: function (progressEvent) {/ / a pair of native progress events}, / / `maxContentLength` defines the maximum size of the allowed response content maxContentLength: 2000 / / `validateStatus` defines whether the status code for a given HTTP response is resolve or reject promise. If `validateStatus` returns `true` (or set to `null` or `undefined`), promise will be resolve;. Otherwise, promise will be rejecte validateStatus: function (status) {return status > = 200 & & status
< 300; // 默认的 }, // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目 // 如果设置为0,将不会 follow 任何重定向 maxRedirects: 5, // 默认的 // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项: // `keepAlive` 默认没有启用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定义代理服务器的主机名称和端口 // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据 // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用于取消请求的 cancel token // (查看后面的 Cancellation 这节了解更多) cancelToken: new CancelToken(function (cancel) { })} 示例(三) 我们还可以使用自定义配置新建一个 axios 实例,并且可以在请求或响应被 then 或 catch 处理前拦截它们。 // 如文件名叫http.jsimport axios from 'axios'// 创建实例时设置配置的默认值var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'}});// 添加请求拦截器instance.interceptors.request.use(function (config) { // 在发送请求之前做些什么 /** 1、比如添加token之类的请求头信息 2、添加每次请求loading等 */ return config;}, function (error) { // 对请求错误做些什么 return Promise.reject(error);});// 添加响应拦截器instance.interceptors.response.use(function (response) { // 对响应数据做点什么 /** 1、集中处理响应数据(如错误码处理) */ return response;}, function (error) { // 对响应错误做点什么 return Promise.reject(error);});export default instance 如何使用上面的http.js??? import http from 'xxx/http'http({ method: 'POST', url: '/user', data: { name: 'Javan', website: 'www.javanx.cn' }}).then((response) =>{/ 200Response}, (err) = > {/ / 500Response})
Example (4)
How to cancel the interface?
Scenario: a search box, each input character will call the interface, there is no way to know which interface data is put back for the last time, can only cancel the same interface initiated before, so there is a cancel interface.
Var CancelToken = axios.CancelToken;var source = CancelToken.source (); axios.get ('/ user/12345', {cancelToken: source.token}) .catch (function (thrown) {if (axios.isCancel (thrown)) {console.log ('Request canceled', thrown.message);} else {/ / handling error}}); / / cancel request (message parameter is optional) source.cancel (' Operation canceled by the user.') After reading this, the article "how to use the axios of vue" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.