Axios GET与POST请求参数传递详解及配置指南

作者:工具松鼠

时间:2026-10-25

浏览:261

本文详细介绍Axios在浏览器和Node.js环境中的使用,涵盖安装、GET与POST请求的参数传递方式、并发请求处理、实例创建、请求配置优先级及拦截器用法。重点解析POST请求中后端接收不到数据的常见原因及正确传参方法,帮助开发者规范使用Axios进行HTTP通信。

文章目录

Axios简介

Axios是一个基于Promise设计的HTTP客户端,适用于浏览器和Node.js环境

核心特性包括:

兼容浏览器与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文件中引入该库

import axios from "axios";

由于axios发布时间早于Vue,无法使用use方法,需将其挂载至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>

另一种GET请求写法:

<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将结果解构为独立响应对象

三、axios API接口

(一)通过传递配置对象创建请求 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请求 传递参数内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章