axios 网络请求 get post

本文介绍了如何在项目中安装并使用Axios进行GET和POST请求,提供了简洁和详细的写法示例,包括安装Axios和querystring库的过程以及如何在Vue组件中调用它们进行数据获取。

Axios 是一个基于 promise 的网络请求库

 1. 在代码目录下安装npm install --save axios   

  在组件页面引用

 import axios from "axios"

2. 在代码目录下安装npm install --save querystring

   import qs from 'qs'

3. get和post请求方式,详细和简洁写法

   <script>
   import axios from "axios"
   import qs from 'qs'

   export default{
     name: 'SecondComponent',
     data(){
        return{
            message:"我是secondComponent的数据"
        }
     },
     mounted(){ 
//get请求简洁写法
        axios.get("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php")
            .then(res =>{
                console.log(res.data);
            })
// post请求简洁写法
        axios.post("http://iwenwiki.com/api/blueberrypai/login.php",qs.stringify({
            user_id:"iwen@qq.com",
                password:"iwen123",
                verification_code:"crfvw"
        })).then(res =>{
            console.log(res.data);
        })

// get请求详细写法
        axios({
            method:"get",
            url:"http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php"
        }).then(res =>{
            console.log(res.data);
        })//详细

// post请求详细写法
        axios({
            method:"post",
            url:"http://iwenwiki.com/api/blueberrypai/login.php",
            data:querystring.stringify({
                user_id:"iwen@qq.com",
                password:"iwen123",
                verification_code:"crfvw"
            })
        }).then(res =>{
            console.log(res.data);
        })
     }
   }
   </script>
   

<think> 我们之前已经讨论过在Axios中实现自定义协议扩展的方法,现在用户的问题是如何使用这个扩展的自定义协议来进行GETPOST请求。用户参考的引用中提到了GETPOST请求在参数传递上的不同(引用[1]),以及Axios的基本使用(引用[2,3])。因此,我们只需要将自定义协议的支持融入到GETPOST请求中即可。 根据之前的实现,我们已经创建了一个支持自定义协议的Axios实例(customProtocolAxios)。这个实例通过拦截器自动处理了协议协商的头信息(X-Custom-Protocols和X-Active-Protocol)。因此,用户在使用这个实例发送GETPOST请求时,不需要额外处理协议协商的部分。 具体步骤: 1. 使用之前创建的customProtocolAxios实例。 2. 发送GET请求时,参数通过`params`属性传递,因为GET请求的参数是作为URL查询字符串发送的(如引用[1]所述)。 3. 发送POST请求时,参数通过`data`属性传递,因为POST请求的参数是在请求体中发送的(如引用[1]所述)。 注意:自定义协议的支持已经在拦截器中自动完成,所以用户只需要像普通请求一样使用即可。 示例代码: 1. GET请求示例: 使用自定义协议实例发送GET请求,参数通过params传递。 2. POST请求示例: 使用自定义协议实例发送POST请求,参数通过data传递。 另外,我们还需要考虑服务端如何根据自定义协议处理请求。服务端需要检查请求头中的协议信息(X-Custom-Protocols和X-Active-Protocol),并按照协商的协议处理请求(如之前服务端示例所示)。 下面给出具体代码示例: </think> ### 使用 Axios 通过自定义协议进行 GET/POST 请求的方法 #### 一、自定义协议集成核心步骤 1. **创建支持自定义协议的 Axios 实例** ```javascript const protocolAxios = axios.create({ // 声明支持的协议版本(自定义配置项) protocols: ['myproto-v1', 'myproto-v2'], // 设置协议认证密钥(可选) protocolSecret: 'your-secret-key' }); ``` 2. **添加协议协商拦截器** ```javascript // 请求拦截器注入协议头 protocolAxios.interceptors.request.use(config => { // 注入协议标识(兼容GET/POST) config.headers['X-Client-Protocols'] = config.protocols.join(',') config.headers['X-Protocol-Version'] = localStorage.getItem('activeProtocol') || config.protocols[0] // POST请求添加协议签名(引用[1]数据封装特性) if (config.method === 'post' && config.data) { config.data.protocolSign = generateSign(config.data, config.protocolSecret) } return config }); // 响应拦截器处理协议协商 protocolAxios.interceptors.response.use(response => { // 更新协商后的协议版本 if (response.headers['x-server-protocol']) { localStorage.setItem('activeProtocol', response.headers['x-server-protocol']) } return response }, error => { // 处理协议不匹配的错误(406状态码) if (error.response?.status === 406) { console.error(`协议不兼容,服务端支持: ${error.response.headers['x-supported-protocols']}`) } return Promise.reject(error) }); ``` #### 二、GET 请求实现方案 ```javascript // GET请求(参数通过URL传递) protocolAxios.get('/api/data', { params: { // 引用[1]GET参数传递方式 id: 123, type: 'custom' }, protocols: ['myproto-v2'] // 可覆盖实例默认协议 }).then(response => { console.log('GET响应:', response.data) }) ``` #### 三、POST 请求实现方案 ```javascript // POST请求(参数通过body传递) protocolAxios.post('/api/submit', { name: 'John', value: 42, // 引用[1]POST数据封装方式 timestamp: Date.now() }, { protocols: ['myproto-v1'], // 指定协议版本 protocolSecret: 'enhanced-key' // 动态密钥 }).then(response => { console.log('POST响应:', response.data) }) ``` #### 四、服务端协议处理示例(Node.js/Express) ```javascript // 协议中间件 app.use((req, res, next) => { const clientProtocols = req.headers['x-client-protocols'].split(',') const version = req.headers['x-protocol-version'] // 验证协议兼容性 const supported = ['myproto-v1', 'myproto-v2', 'myproto-v3'] const selected = supported.find(p => clientProtocols.includes(p)) if (!selected) { return res.status(406).header('X-Supported-Protocols', supported.join(',')).send() } // POST请求验证签名 if (req.method === 'POST') { const sign = req.body?.protocolSign if (!validateSign(req.body, sign)) { return res.status(401).send('Invalid protocol signature') } } // 返回协商结果 res.header('X-Server-Protocol', selected) next() }) ``` #### 五、协议交互流程对比 | 请求类型 | 参数位置 | 协议处理要点 | 安全增强 | |----------|---------------|------------------------------|------------------------| | **GET** | URL查询参数 | 通过Header传递协议版本 | 参数需URL编码[^1] | | **POST** | Request Body | 在Body中添加协议签名 | 敏感数据加密传输[^2] | > **最佳实践**: > 1. 关键操作使用POST+协议签名组合(如支付、配置修改) > 2. 频繁读取操作使用GET+协议版本缓存 > 3.Vue/React中全局注入协议实例(引用[3]引入方式)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值