Axios get post请求传递参数的实现代码

目录
  • Axios概述
  • 一、 安装
  • 三、 axiosAPI
  • 四、请求配置
  • 五、响应内容
  • 六、默认配置
  • 七、拦截器
  • 八、错误处理
  • 九、取消

Axios概述

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

特点 :

支持浏览器和node.js

支持promise

能拦截请求和响应

能转换请求和响应数据

能取消请求

自动转换json数据

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

一、 安装

npm安装

$ npm install axios
bower安装

$ bower install axios
通过cdn引入

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

首先需要安装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请求

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

另外一种形式:

<input id="get02Id" type="button" value="get02"/>
<script>
    $("#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);
            })
    })
</script>

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

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

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

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

<input id="post01Id" type="button" value="post01"/>
<script>
    $("#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);
            });
    })
</script>

3.执行多个并发请求

<input id="button01Id" type="button" value="点01"/>
<script>
    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);
            }))
    })
</script>

另外一种形式:

<input id="button02Id" type="button" value="点02"/>
<script>
    $("#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);
            }))
    })
</script>

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

三、 axiosAPI

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

<input id="buttonId" type="button" value="点"/>
<script>
    $("#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
        });
    })
</script>

axios(url[,config])

<input id="buttonId" type="button" value="点"/>
<script>
    $("#buttonId").click(function () {
        // 发起一个get请求,(get是默认的请求方法)
        axios('http://localhost:8080/user/getWord');
    })
</script>

(二)请求方法别名

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 < 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: 'lisi',
            password: '54321'
        }
    },
​
    //  cancelToken 指定用于取消请求的 cancel token
    cancelToken: new CancelToken(function (cancel) {
    })
}

五、响应内容

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

可以这样来获取响应信息

<input id="getId" type="button" value="get"/>
<script>
    $("#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);
            })
    })
</script>

六、默认配置

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

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

八、错误处理

<input id="getId" type="button" value="get"/>
<script>
    $("#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);
            });
    })
</script>

九、取消

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

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

<input id="getId" type="button" value="get"/>
<input id="unGetId" type="button" value="unGet"/>
<script>
    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("操作被用户取消");
    });
</script>

到此这篇关于axios get post请求 传递参数的文章就介绍到这了,更多相关axios get post请求 传递参数内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Vue axios全局拦截 get请求、post请求、配置请求的实例代码

    下面通过一段代码给大家介绍Vue axios全局拦截 get请求.post请求.配置请求,具体代码如下所述: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../node_modules/vue/dist/vue.js"&g

  • vue axios数据请求get、post方法及实例详解

    我们常用的有get方法以及post方法,下面简单的介绍一下这两种请求方法 vue中使用axios方法我们先安装axios这个方法 npm install --save axios 安装之后采用按需引入的方法,哪个页面需要请求数据就在哪个页面里引入一下. import axios from 'axios' 引入之后我们就可以进行数据请求了,在methods中创建一个方法 methods:{ getInfo(){ let url = "url" axios.get(url).then((r

  • vue如何封装Axios的get、post请求

    目录 封装Axios的get.post请求 1.封装Axios基础配置 2.封装网络请求 3.vue中使用 vue axios两种方法(封装和不封装)get请求和post请求 一.没有封装的用法 二.封中之后的用法 封装Axios的get.post请求 Axios在vue项目中用的较多,每次都要写一遍很是不方便,尤其其中的config配置项是公用的,完全可以封装一下,这样下次再用就可以直接CV了!毕竟CV大法香啊! 1.封装Axios基础配置 创建一个request.js 文件,内容如下,我把解

  • vue中axios处理http发送请求的示例(Post和get)

    本文介绍了vue中axios处理http发送请求的示例(Post和get),分享给大家,具体如下: axios中文文档 https://github.com/mzabriskie/axios#using-applicationx-www-form-urlencoded-format   axios文档 在处理http请求方面,已经不推荐使用vue-resource了,而是使用最新的axios,下面做一个简单的介绍. 安装 使用node npm install axios 使用cdn <scrip

  • Axios get post请求传递参数的实现代码

    目录 Axios概述 一. 安装 三. axiosAPI 四.请求配置 五.响应内容 六.默认配置 七.拦截器 八.错误处理 九.取消 Axios概述 首先,axios是基于promise用于浏览器和node.js的http客户端 特点 : 支持浏览器和node.js 支持promise 能拦截请求和响应 能转换请求和响应数据 能取消请求 自动转换json数据 浏览器端支持防止CSRF(跨站请求伪造) 一. 安装 npm安装 $ npm install axiosbower安装 $ bower

  • Spring Boot/VUE中路由传递参数的实现代码

    在路由时传递参数,一般有两种形式,一种是拼接在url地址中,另一种是查询参数.如:http://localhost:8080/router/tang/101?type=spor&num=12.下面根据代码看一下,VUE 和 Spring Boot 中各自是如何处理传递和接受参数的. Spring Boot package com.tang.demo1.controller; import org.springframework.web.bind.annotation.*; @RestContro

  • Shell脚本通过参数名传递参数的实现代码

    平常在写shell脚本都是用$1,$2-这种方式来接收参数,然而这种接收参数的方式不但容易忘记且不易于理解和维护.Linux常用的命令都可指定参数名和参数值,然而我们怎样才能给自己的shell脚本也采用参数名和参数值这样的方式来获取参数值呢?而不是通过$1,$2这种方式进行获取.下面的例子定义了短参数名和长参数名两种获取参数值的方式.其实是根据getopt提供的特性进行整理而来. #!/bin/bash while getopts i:o:p:s:t: OPT; do case ${OPT} i

  • 解决PHP使用CURL发送GET请求时传递参数的问题

    最近在使用curl发送get请求的时候发现传递参数一直没有生效,也没有返回值,以为是自己哪里写错了,网上找东西时也没有人专门来说get请求传递参数的内容,所以,今天在这里记录一下,希望可以帮到一些人 get请求是最简单的请求,不过要注意自己的请求是http请求还是https的请求,因为https请求时要关闭SSL验证,不然验证通不过,没有办法请求到数据: GET请求的参数 get传递参数和正常请求url传递参数的方式一样 function get_info($card){ $url ="http

  • Vue系列:通过vue-router如何传递参数示例

    使用vue-router 来实现webapp的页面跳转,有时候需要传递参数,做法如下: 参考文献:http://router.vuejs.org/en/named.html 主要有以下几个步骤: (1) 设置好路由配置 router.map({ '/history/:deviceId/:dataId': { name: 'history', // give the route a name component: { ... } } }) 这里有2个关键点: a)给该路由命名,也就是上文中的 na

  • axios 发 post 请求,后端接收不到参数的完美解决方案

    目录 问题场景 问题原因 要点1 要点2 问题分析 解决方案 解决方案一 解决方案二 解决方案三 解决方案四 解决方案五 解决方案六 问题场景 场景很简单,就是一个正常 axios post 请求: axios({ headers: { 'deviceCode': 'A95ZEF1-47B5-AC90BF3' }, method: 'post', url: '/api/lockServer/search', data: { username, pwd } }) 后台说没有接收到你的传参. 这就有

  • Angularjs中$http以post请求通过消息体传递参数的实现方法

    本文实例讲述了Angularjs中$http以post请求通过消息体传递参数的方法.分享给大家供大家参考,具体如下: Angularjs中,$http以post在消息体中传递参数,需要做以下修改,以确保消息体传递参数的正确性. 一.在声明应用的时候进行设置: var httpPost = function($httpProvider) { /******************************************* 说明:$http的post提交时,纠正消息体 ***********

  • axios发送post请求springMVC接收不到参数的解决方法

    axios发送post请求时,出现了参数后台接收不到的情况,分析了下请求,发现是请求头content-type不对,是application/json,正常应该是application/x-www-form-urlencoded. 解决方法有以下三种: 1.设置axios的默认请求头 //设置全局的 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; var instance = a

  • vue+axios全局添加请求头和参数操作

    走登录的接口都会返回一个token值,然后存起来方便之后调接口的时候给后台传过去,传给后台的方式有两种:(具体使用哪种需要和后台商量) 1.放在请求头中 2.放在接口的参数中 1.放在请求头中 下面代码是从本地cookie中拿token VueCookie:一个用于处理浏览器cookies的简单Vue.js插件. // 在封装axios的文件中添加拦截器 // 添加请求拦截器,在请求头中加token service.interceptors.request.use( config => { //

  • Filter中获取传递参数方式(解决post请求参数问题)

    目录 Filter中获取传递参数 1. GET 传递 2. Post 传递 XyRequestWrapper 类 XySecurityFilter Filter中获取传递参数 1. GET 传递 参数可以直接通过request.getParameter获取. 2. Post 传递 产生不能过直接从request.getInputStream() 读取,必须要进行重新写.(request.getInputStream()只能够读取一次) 方式: 通过重写 HttpServletRequestWra

随机推荐