vuehttp的简单介绍
本篇文章给大家谈谈vuehttp,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
vue的http请求主要是用什么插件
axios
基于 Promise 的 HTTP 请求客户端,可同时在浏览轿姿铅器和 node.js 中使用
功能特性
在浏览器中发送 XMLHttpRequests 请求
在 node.js 中发送 http请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
自动转换 JSON 数据
客户端支持保护安全免受 XSRF 攻击
安装
使用 bower:
$ bower install axios
使用 npm:
$ npm install axios
例子
发送一个 GET 请求册散
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
发送一个 POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
闭好})
.catch(function (response) {
console.log(response);
});
发送多个并发请求
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(config)
// Send a POST requestaxios({ method: 'post', url: '/user/12345',
data: { firstName: 'Fred', lastName: 'Flintstone' }});
axios(url[, config])
// Sned a GET request (default method)
axios('/user/12345');
请求方法别名
为方便起见,我们为所有支持的请求方法都提供了别名
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
注意
当使用别名方法时, url、 method 和 data 属性不需要在 config 参数里面指定。
并发
处理并发请求的帮助方法
axios.all(iterable)
axios.spread(callback)
创建一个实例
你可以用自定义配置创建一个新的 axios 实例。
axios.create([config])
var instance = axios.create({
baseURL: '',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'
}});
实例方法
所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, 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: '',
// `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 or an ArrayBuffer
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
params: {
ID: 12345
},
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. , )
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 a string, an ArrayBuffer or a hash
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'
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
}
}
响应的数据结构
响应的数据包括下面的信息:
{
// `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: {}
}
当使用 then 或者 catch 时, 你会收到下面的响应:
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 = '';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定义实例默认配置
// Set config defaults when creating the instance
var instance = axios.create({
baseURL: ''
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置的优先顺序
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.
// 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 libraryvar instance = axios.create();
// Override timeout default for the library
// Now all requests 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});
拦截器
你可以在处理 then 或 catch 之前拦截请求和响应
// 添加一个请求拦截器
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);
});
// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
移除一个拦截器:
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
你可以给一个自定义的 axios 实例添加拦截器:
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
错误处理
axios.get('/user/12345')
.catch(function (response) {
if (response instanceof Error) {
// Something happened in setting up the request that triggered an Error
console.log('Error', response.message);
} else {
// The request was made, but the server responded with a status code
// that falls out of the range of 2xx
console.log(response.data);
console.log(response.status);
console.log(response.headers);
console.log(response.config);
}
});
Promises
axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入 polyfill
[img]Vue 路由和Http
命令行中输入 npm install vue-router --save-dev
要想使用路由,要在main.js文件中引入vue-router路由模块--- import VueRouter from 'vue-router'
Vue.use(VueRouter)
(1)注明要使用这个路由之后,就可以在下方配置路由--- const router = new VueRouter({})
(2)括号中传递对象,对象的参数是固定的。
(3)参数routes是个数组,数组里面可以拥有对应的对象。
(4)对象中的第一个参数是path,path是要路由的地址,比如下例我们的路由地址是根路径"/"
(5)对象中的第二个参做哪数是component,如果抓到了路由的地址,需要调用一个component,component可以跳转到对应的组件地址
现在这个路由并不能被使用,因为找纯州码不到Home和HelloWorld组件。所以,我们引进Home和HelloWorld组件。(注意:这里HelloWorld组件已存在,Home组件还未创建)
import HelloWorld from './components/HelloWorld'
import Home from './components/Home'
(1)首先,在components文件夹下建立Home.vue组件
(2)我们要让 Home.vue成为Header.vue和Footer.vue和Users.vue的父级
(3)操作Home.vue如下,然后将App.vue中的组件和import内容清除
现在可以找到路由地址“/”,也能执行Home组件,但是没有告诉系统在哪里展示这个Home组件。这里根组件是App,所以要在App.vue当中输入对应内容。 router-view/router-view
上图url处仔细观察会发现,有多余的#/标识,需要去掉。因为我们自己定义路由,点击实现的时候会有问题。
在配置路由时加入一个属性 mode:"history" ,就可以去掉了
功能和a标签一致,只是点击不会每次都发送请求,刷新页面,所以项迹衡目运行速率好很多。
Vue 路由拦截、http拦截
第一步:路由拦截
定义完路由后,我们主要是利用vue-router提供的钩子函数beforeEach()对路由进行判断。
每个钩子方法接收三个参数:
其中,to.meta中是我们自定义的数据,其中就包括我们刚刚定义的requireAuth字段。通过这个字段来判断该路由是否需要登录权限。需要的话,同时当前应用不存在token,则跳转到登录页面,进行登录。登录成功后跳转到目标路由。
登录拦截到这里就结束了吗?并没有。这种方式只是简单的前端路由控制,并不能真正阻止用户访问需要登录权限的路由。还有一种情况便是:当前token失效了,但是token依然保存在本地。这时候你去访问需要登录权限的路由时,实际上应该让用户重新登录。
这时候就需要结合 http 拦截器 + 后端接口返回的http 状态码谨桐郑来判断。
要想统一处理所有http请求和响应,就得用上 axios 的拦截器。通过配置http response inteceptor,当后端接口返回401 Unauthorized(未授权),让用户重新登录。
拦截器
这样我们就统一处理了http请求和响应的拦截.当然祥颂我们可以根据具体的业务要求更改拦截轮锋中的处理.
原文链接:
更多精彩请关注: Vue专题
解决Vue http中的跨域问题
在平常的项目开发当中,很模宴容易遇到跨域的问题,好在vue-cli的脚手架提供了跨域的解决方案,在config下的index.js中有个proxyTable属性,在其中添加如下配置:
proxyTable: {
'/api':{
target:'',
changeOrigin:true,
pathRewrite:{
}
}
如上所示,如果在8090后在加路径,则无效(亲测);
在pathRewite中可以添加替换,因为在正常代理过后会在路渣瞎径结尾有ap这个路径,所以如果实际的地址和这个不同旦梁银,则可以进行替换。
关于vuehttp和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。