axios get post请求 传递参数 您所在的位置:网站首页 1660tiadoc参数 axios get post请求 传递参数

axios get post请求 传递参数

2023-07-20 09:29| 来源: 网络整理| 查看: 265

Axios概述 :

首先,axios是基于promise用于浏览器和node.js的http客户端

特点 :

支持浏览器和node.js

支持promise

能拦截请求和响应

能转换请求和响应数据

能取消请求

自动转换json数据

浏览器端支持防止CSRF(跨站请求伪造)

一、 安装 npm安装

$ npm install axios bower安装

$ bower install axios 通过cdn引入

首先需要安装axios 下一步,在main.js中引入axios

import axios from "axios";

与很多第三方模块不同的是,axios不能使用use方法,由于axios比vue出来的早 所以需要放到vue的原型对象中

Vue.prototype.$axios = axios;

接着,我们就可以在App.vue中使用axios了

created:function(){ this.$axios.get("/seller",{"id":123}).then(res=>{ console.log(res.data); }); }

1.发起一个get请求

$("#get01Id").click(function () { axios.get('http://localhost:8080/user/findById?id=1') .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }) })

另外一种形式:

$("#get02Id").click(function () { axios.get('http://localhost:8080/user/findById', { params: { id: 1 } }) .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }) })

2.发起一个post请求 在官方文档上面是这样的:

axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }).then(function (res) { console.log(res); }).catch(function (err) { console.log(err); });

但是如果这么写,会导致后端接收不到数据

所以当我们使用post请求的时候,传递参数要这么写:

$("#post01Id").click(function () { var params = new URLSearchParams(); params.append('username', 'sertyu'); params.append('password', 'dfghjd'); axios.post('http://localhost:8080/user/addUser1', params) .then(function (value) { console.log(value); }) .catch(function (reason) { console.log(reason); }); })

3.执行多个并发请求

function getUser1() { return axios.get('http://localhost:8080/user/findById?id=1'); } ​ function getUser2() { return axios.get('http://localhost:8080/user/findById?id=2'); } ​ $("#buttonId").click(function () { axios.all([getUser1(), getUser2()]) .then(axios.spread(function (user1, user2) { alert(user1.data.username); alert(user2.data.username); })) })

另外一种形式:

$("#button02Id").click(function () { axios.all([ axios.get('http://localhost:8080/user/findById?id=1'), axios.get('http://localhost:8080/user/findById?id=2') ]) .then(axios.spread(function (user1, user2) { alert(user1.data.username); alert(user2.data.username); })) })

当所有的请求都完成后,会收到一个数组,包含着响应对象,其中的顺序和请求发送的顺序相同,可以使用axios.spread分割成多个单独的响应对象

三、 axiosAPI (一)可以通过向axios传递相关配置来创建请求 axios(config)

$("#buttonId").click(function () { var params = new URLSearchParams(); params.append('username','trewwe'); params.append('password','wertyu'); // 发起一个post请求 axios({ method:'post', url:'http://localhost:8080/user/addUser1', data:params }); })

axios(url[,config])

$("#buttonId").click(function () { // 发起一个get请求,(get是默认的请求方法) axios('http://localhost:8080/user/getWord'); })

(二)请求方法别名

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

在使用别名方法时,url、method、data这些属性都不必在配置中指定

(三)并发请求,即是帮助处理并发请求的辅助函数

//iterable是一个可以迭代的参数如数组等 axios.all(iterable) //callback要等到所有请求都完成才会执行 axios.spread(callback)

(四)创建实例,使用自定义配置 1.axios.create([config])

var instance = axios.create({ baseURL:"http://localhost:8080/user/getWord", timeout:1000, headers: {'X-Custom-Header':'foobar'} });

2.实例的方法

以下是实例方法,注意已经定义的配置将和利用create创建的实例的配置合并

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 是用于请求的服务器 URL url: '/user/getWord', ​ // method 是创建请求时使用的方法 method: 'get', // 默认是 get ​ // baseURL 将自动加在 url 前面,除非 url 是一个绝对路径。 // 它可以通过设置一个 baseURL 便于为 axios 实例的方法传递相对路径 baseURL: 'http://localhost:8080/', ​ // transformRequest 允许在向服务器发送前,修改请求数据 // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) { // 对 data 进行任意转换处理 ​ return data; }], ​ // transformResponse 在传递给 then/catch 前,允许修改响应数据 transformResponse: [function (data) { // 对 data 进行任意转换处理 ​ return data; }], ​ // headers 是即将被发送的自定义请求头 headers: {'X-Requested-With': 'XMLHttpRequest'}, ​ // params 是即将与请求一起发送的 URL 参数 // 必须是一个无格式对象(plain object)或 URLSearchParams 对象 params: { ID: 12345 }, ​ // paramsSerializer 是一个负责 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 是作为请求主体被发送的数据 // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH' // 在没有设置 transformRequest 时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 浏览器专属:FormData, File, Blob // - Node 专属: Stream data: { firstName: 'yuyao' }, ​ // timeout 指定请求超时的毫秒数(0 表示无超时时间) // 如果请求话费了超过 timeout 的时间,请求将被中断 timeout: 1000, ​ // withCredentials 表示跨域请求时是否需要使用凭证 withCredentials: false, // 默认的 ​ // adapter 允许自定义处理请求,以使测试更轻松 // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)). adapter: function (config) { /* ... */ }, ​ // auth 表示应该使用 HTTP 基础验证,并提供凭据 // 这将设置一个 Authorization 头,覆写掉现有的任意使用 headers 设置的自定义 Authorization 头 auth: { username: 'zhangsan', password: '12345' }, ​ // responseType 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默认的 ​ // xsrfCookieName 是用作 xsrf token 的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN', // default ​ // xsrfHeaderName 是承载 xsrf token 的值的 HTTP 头的名称 xsrfHeaderName: 'X-XSRF-TOKEN', // 默认的 ​ // onUploadProgress 允许为上传处理进度事件 onUploadProgress: function (progressEvent) { // 对原生进度事件的处理 }, ​ // onDownloadProgress 允许为下载处理进度事件 onDownloadProgress: function (progressEvent) { // 对原生进度事件的处理 }, ​ // maxContentLength 定义允许的响应内容的最大尺寸 maxContentLength: 2000, ​ // validateStatus 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。 // 如果 validateStatus 返回 true (或者设置为 null 或 undefined ),promise 将被 resolve; 否则,promise 将被 rejecte validateStatus: function (status) { return status >= 200 && status keepAlive: true}), ​ // 'proxy' 定义代理服务器的主机名称和端口 // auth 表示 HTTP 基础验证应当用于连接代理,并提供凭据 // 这将会设置一个 Proxy-Authorization 头,覆写掉已有的通过使用 header 设置的自定义 Proxy-Authorization 头。 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'lisi', password: '54321' } }, ​ // cancelToken 指定用于取消请求的 cancel token cancelToken: new CancelToken(function (cancel) { }) }

五、响应内容

{ data:{}, status:200, //从服务器返回的http状态文本 statusText:'OK', //响应头信息 headers: {}, //config是在请求的时候的一些配置信息 config: {} }

可以这样来获取响应信息

$("#getId").click(function () { axios.get('http://localhost:8080/user/findById?id=1') .then(function (value) { console.log("data:"+value.data); console.log("status:"+value.status); console.log("statusText:"+value.statusText); console.log("headers:"+value.headers); console.log("config:"+value.config); }) .catch(function (reason) { console.log(reason); }) })

六、默认配置 默认配置对所有请求都有效

1、全局默认配置

axios.defaults.baseURL = 'http://localhost:8080/'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';

2、自定义的实例默认设置

//当创建实例的时候配置默认配置 var instance = axios.create({ baseURL: 'http://localhost:8080/' }); //当实例创建时候修改配置 instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;

3、配置中有优先级 config配置将会以优先级别来合并,顺序是lib/defauts.js中的默认配置,然后是实例中的默认配置,最后是请求中的config参数的配置,越往后等级越高,后面的会覆盖前面的例子。

//创建一个实例的时候会使用libray目录中的默认配置 //在这里timeout配置的值为0,来自于libray的默认值 var instance = axios.create(); //回覆盖掉library的默认值 //现在所有的请求都要等2.5S之后才会发出 instance.defaults.timeout = 2500; //这里的timeout回覆盖之前的2.5S变成5s instance.get('/longRequest',{ timeout: 5000 });

七、拦截器 1.可以在请求、响应在到达then/catch之前拦截

//添加一个请求拦截器 axios.interceptors.request.use(function(config){ //在请求发出之前进行一些操作 return config; },function(err){ //Do something with request error return Promise.reject(error); }); //添加一个响应拦截器 axios.interceptors.response.use(function(res){ //在这里对返回的数据进行处理 return res; },function(err){ //Do something with response error return Promise.reject(error); })

2.取消拦截器

var myInterceptor = axios.interceptor.request.use(function(){/*....*/}); axios.interceptors.request.eject(myInterceptor);

3.给自定义的axios实例添加拦截器

var instance = axios.create(); instance.interceptors.request.use(function(){})

八、错误处理

$("#getId").click(function () { axios.get('http://localhost:8080/user/findById?id=100') .catch(function (error) { if (error.response) { //请求已经发出,但是服务器响应返回的状态吗不在2xx的范围内 console.log("data:"+error.response.data); console.log("status:"+error.response.status); console.log("header:"+error.response.header); } else { //一些错误是在设置请求的时候触发 console.log('Error', error.message); } console.log(error.config); }); })

九、取消 通过一个cancel token来取消一个请求

通过CancelToken.source工厂函数来创建一个cancel token

var CancelToken = axios.CancelToken; var source = CancelToken.source(); $("#getId").click(function () { axios.get('http://localhost:8080/user/findById?id=1', { cancelToken: source.token }) .then(function (value) { console.log(value); }) .catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { //handle error } }); }); $("#unGetId").click(function () { //取消请求(信息的参数可以设置的) source.cancel("操作被用户取消"); });


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有