vue根据url获取内容axios_你想要了解的关于vue里面axios的基本知识都在这里了

研究过vue.js的童鞋,对于axios肯定会有些了解,它基于Promise的HTTP客户端,用于浏览器和node.js。那如何去应用它呢?我们一起从最基础的学习起吧。

特征

首先了解下axios的一些主要特征应用:

1、从浏览器发出XMLHttpRequests

2、从node.js发出HTTP请求

3、支持Promise API

4、拦截请求和响应

5、转换请求和响应数据

6、取消请求

7、JSON数据的自动转换

8、客户端支持以防止XSRF

如何安装anios

使用npm:$ npm install axios

使用bower:$ bower install axios

使用yarn:$ yarn add axios

使用cdn:

安装很简单的,接下来我们来看些如何在实际项目中的应用。

实例应用

注意:CommonJS用法

为了在将CommonJS导入与require()一起使用时获得TypeScript类型(用于智能/自动完成),请使用以下方法:const axios = require('axios').default;

// axios。现在将提供自动完成和参数输入

执行GET请求const axios = require('axios');

// Make a request for a user with a given ID

axios.get('/user?ID=12345')

.then(function (response) {

// handle success

console.log(response);

})

.catch(function (error) {

// handle error

console.log(error);

})

.finally(function () {

// always executed

});

// Optionally the request above could also be done as

axios.get('/user', {

params: {

ID: 12345

}

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

})

.finally(function () {

// always executed

});

// Want to use async/await? Add the `async` keyword to your outer function/method.

async function getUser() {

try {

const response = await axios.get('/user?ID=12345');

console.log(response);

} catch (error) {

console.error(error);

}

}注意:async / await是ECMAScript 2017的一部分,并且Internet Explorer和旧版浏览器不支持async / await,因此请谨慎使用。

执行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');

}

axios.all([getUserAccount(), getUserPermissions()])

.then(axios.spread(function (acct, perms) {

// Both requests are now complete

}));

axios API

可以通过将相关配置传递给axios来发出请求。

axios(配置)// Send a POST request

axios({

method: 'post',

url: '/user/12345',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

}

});// GET request for remote image

axios({

method: 'get',

url: 'http://bit.ly/2mTM3nY',

responseType: 'stream'

})

.then(function (response) {

response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))

});

axios(URL [,config])// Send a GET request (default method)

axios('/user/12345');

Request method aliases

为了方便起见,aliases已为所有受支持的请求方法。axios.request(配置)

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]])

注意

使用别名方法时,无需在config中指定url,method和data属性。

并发

帮助程序功能,用于处理并发请求。axios.all(可迭代)

axios.spread(回调)

创建一个实例

您可以使用自定义配置创建axios的新实例。

axios.create([config])const instance = axios.create({

baseURL: 'https://some-domain.com/api/',

timeout: 1000,

headers: {'X-Custom-Header': 'foobar'}

});

实例方法

可用的实例方法在下面列出。指定的配置将与实例配置合并。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#getUri([config])

请求配置

这些是发出请求的可用配置选项。仅URL是必需的。如果未指定method,则请求将默认为GET。{

// `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.

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

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', 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

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

// 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

onUploadProgress: function (progressEvent) {

// Do whatever you want with the native progress event

},

// `onDownloadProgress` allows handling of progress events for downloads

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

maxContentLength: 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 and port 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`.

proxy: {

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) {

})

}

响应模式

请求的响应包含以下信息。{

// `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 headers that the server responded with

// All header names are lower cased

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);

});

当使用catch或将拒绝回调作为then的第二个参数传递时,响应将通过错误对象提供,如“处理错误”部分所述。

配置默认值

您可以指定将应用于每个请求的配置默认值。

全局axios默认值axios.defaults.baseURL = 'https://api.example.com';

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定义实例默认值//创建实例时设置默认配置

const instance = axios.create({

baseURL:“ https://api.example.com”

});

//创建实例后更改默认值

instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;

配置优先顺序

Config将以优先顺序合并。顺序是在lib / defaults.js中找到库默认值,然后是实例的defaults属性,最后是请求的config参数。后者将优先于前者。这是一个例子。//使用库提供的配置默认值创建实例

//此时,超时配置值为0,这是库的默认值

const instance = axios.create();

//默认情况下,库的超时超时

//现在使用此实例的所有请求将等待2.5秒,然后再超时

instance.defaults.timeout = 2500;

//覆盖此请求的超时时间,因为它需要花费很长时间

instance.get('/ longRequest',{

timeout:5000

});

拦截器

您可以先拦截请求或响应,然后再进行捕获或捕获。//添加请求拦截器

axios.interceptors.request.use(function (config) {

//在发送请求之前先做点事

return config;

}, function (error) {

//发生请求错误

return Promise.reject(error);

});

//添加响应拦截器

axios.interceptors.response.use(function (response) {

//处于2xx范围内的任何状态代码都会导致此函数触发

//对响应数据进行处理

return response;

}, function (error) {

//任何超出2xx范围的状态代码都会触发此函数

//做一些响应错误

return Promise.reject(error);

});

如果以后需要删除拦截器,则可以。const myInterceptor = axios.interceptors.request.use(function(){/*...*/});

axios.interceptors.request.eject(myInterceptor);

您可以将拦截器添加到axios的自定义实例中。const instance = axios.create();

instance.interceptors.request.use(function(){/*...*/});

处理错误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`是浏览器中XMLHttpRequest的实例,也是

// node.js中的http.ClientRequest

console.log(error.request);

} else {

//设置触发错误的请求时发生了什么

console.log('Error', error.message);

}

console.log(error.config);

});

使用validateStatus config选项,您可以定义应该引发错误的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());

});

Cancellation

您可以使用cancel token取消请求。

axios取消tokenAPI基于撤回的可取消承诺提议。

您可以使用CancelToken.source工厂创建一个cancel  token,如下所示:const CancelToken = axios.CancelToken;

const source = CancelToken.source();

axios.get('/user/12345', {

cancelToken: source.token

}).catch(function (thrown) {

if (axios.isCancel(thrown)) {

console.log('Request canceled', thrown.message);

} else {

// handle error

}

});

axios.post('/user/12345', {

name: 'new name'

}, {

cancelToken: source.token

})

//取消请求(message参数是可选的)

source.cancel('Operation canceled by the user.');

您还可以通过将执行程序函数传递给CancelToken构造函数来创建cancel token: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 request

cancel();

注意:您可以使用相同的cancel token取消多个请求。

使用application / x-www-form-urlencoded格式

默认情况下,axios将JavaScript对象序列化为JSON。要改为以application / x-www-form-urlencoded格式发送数据,可以使用以下选项之一。

浏览器

在浏览器中,可以如下使用URLSearchParams API:const params = new URLSearchParams();

params.append('param1', 'value1');

params.append('param2', 'value2');

axios.post('/foo', params);

请注意,并非所有浏览器都支持URLSearchParams(请参见caniuse.com),但是有可用的polyfill(确保对全局环境进行polyfill)。

另外,您可以使用qs库对数据进行编码:const qs = require('qs');

axios.post('/ foo',qs.stringify({'bar':123}));

或以另一种方式(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);

Node.js

在node.js中,可以按以下方式使用querystring模块:const querystring = require('querystring');

axios.post('http://something.com/',querystring.stringify({foo:'bar'})));

您也可以使用qs库。

注意:如果需要对嵌套对象进行字符串化处理,则最好使用qs库,因为querystring方法存在该用例的已知问题(https://github.com/nodejs/node-v0.x-archive/issues/1665)。

Promises

axios取决于要支持的本机ES6 Promise实现。如果您的环境不支持ES6 Promises,则可以进行polyfill。

TypeScript

axios包括TypeScript定义。import axios from 'axios';

axios.get('/user?ID=12345');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值