ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 插件-http功能 http功能提供强大的ajax功能,基于Promise ## 示例 一个get请求 ```javascript v.http.get('/user?id=12345') .then(function (response) {console.log(response);}) .catch(function (error) {console.log(error);}); v.http.get('/user', {params: {id: 12345}}).then(function (response) { console.log(response); }) ``` 一个post请求 ```javascript v.http.post('/adduser',{name:'vace',tel:'1888888888'}).then(res => console.log(res)) ``` ## API * `v.http.request(confi)` * `v.http.get(url[, config)` * `v.http.delete(url[, config)` * `v.http.head(url[, config)` * `v.http.post(url[, data[, config])` * `v.http.put(url[, data[, config])` * `v.http.patch(url[, data[, config]])` ## 高级用法,创建一个instance交互实例 ```javascript var instance = v.http.create({ baseURL: 'http://wx.diggid.cn/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); // 此时的instance具有API中的所有方法,且包含基本配置 instance.get('user') ``` ## 参数详解 ```javascript { // `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', and 'PATCH' // The last function in the array must return a string, an ArrayBuffer, or a Stream transformRequest: [function (data) { // 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 data: { firstName: 'Fred' }, // `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, // `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. // Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)). adapter: function (resolve, reject, 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`. auth: { username: 'janedoe', password: 's00pers3cret' } // `responseType` indicates the type of data that the server will respond with // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 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 // `progress` allows handling of progress events for 'POST' and 'PUT uploads' // as well as 'GET' downloads progress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content 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 } ``` ## 响应参数详解 ```javascript { // `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 headers: {}, // `config` is the config that was provided to `axios` for the request config: {} } ``` ## 全局基本配置 ```javascript v.http.defaults.baseURL = 'https://api.example.com'; v.http.defaults.headers.common['Authorization'] = AUTH_TOKEN; v.http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' ```