vue中post请求使用form表单格式发送数据

本文介绍在Vue中如何使用form表单格式发送POST请求,并包含签名计算的业务逻辑,详细展示了请求头设置、数据转换及签名计算的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这一篇是原生vuepost请求使用form表单格式发送数据,里面还掺杂了一些关于算签名业务。可能看起来比较繁琐,不过注释还写的挺全的,可以供大家参考。
html:

<div id="app">
    用户名:<input type="text" style="width: 200px" name="username" v-model="user.username"/>
    密  码:<input type="password" style="width: 200px" name="password" v-model="user.password"/>
    <!--<input type="submit" name="submit" value="登录"/>-->
    <button style="width: 50px;height: 30px;" @click="login()">登录</button>
</div>

js:

new Vue({
    el: '#app',
    data: {
        user: {},
        result: {}
    },
    // 发送post请求时,不能发送 Content-Type: application/json;charset=UTF-8 这个格式,因为后台过滤器要进行处理签名
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',   // 设置请求头为form表单格式
        // 'Content-Type': 'application/json;charset=UTF-8'
    },
    methods: {
        login: function () {
            var _this = this;
            axios({
                method: 'post',
                url: '/noauth/login' + getSign("username=" + _this.user.username + "&password=" + _this.user.password),
                data: {
                    username: _this.user.username,
                    password: _this.user.password
                },
                transformRequest: [function (data) {  // 将{username:111,password:111} 转成 username=111&password=111
                    var ret = '';
                    for (var it in data) {
                        // 如果要发送中文 编码
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret.substring(0,ret.length-1)
                }],
            }).then(function (response) {
             	// 拿到data
                _this.result = response.data;
                console.info(_this.result.message);
				// 将验证信息放入缓存                
				localStorage.setItem("sbkjauth",response.headers["sbkjauth"]);
                if (_this.result.status == "0201") {
                    var url = "/html/index.html";
                    axios({
                        method:"get",
                        url:url+getSign(),
                        headers:{
                            "sbkjauth":localStorage.getItem("sbkjauth")
                        },
                    }).then(function (resp) {
                        console.info(resp.data);
                    })
                }
            }).catch(function (reason) {
                console.error(reason)
            })
        },
    created: function () {  
        console.info("页面尚未加载完成!")
    }
});

其中里面的getSign(“username=” + _this.user.username + “&password=” + _this.user.password),代表的是算签名,会在下一篇博文讲。
如果发现什么问题请留言,毕竟代码都是人写的难免会出错。

### Vue POST 请求 Form-Data 格式传参示例 为了在 Vue 应用程序中以 `form-data` 格式发送 POST 请求,可以使用 Axios 进行网络请求处理。下面是一个完整的例子来展示如何构建并提交包含文件和其他表单字段的数据。 #### 构建 FormData 对象 当需要上传文件以及附加其他信息时,应该先创建一个新的 `FormData()` 实例,并利用其 `append()` 方法依次加入各个键值对[^1]: ```javascript let formData = new FormData(); // 添加常规字符串类型的参数 formData.append('code', 'your_code_value'); formData.append('name', 'your_name_value'); formData.append('type', 'your_type_value'); // 假设 file 是来自 <input type="file"> 的 FileList 对象中的第一个项 const selectedFile = document.querySelector('input[type=file]').files[0]; if (selectedFile) { formData.append('file', selectedFile); // 将文件添加到 formData 中 } ``` #### 使用 Axios 发送 Post 请求 一旦准备好了要传递给服务器端的信息之后,就可以调用 Axios 来发起 HTTP POST 请求了。这里假设已经安装好 axios 并导入到了项目里[^3]: ```javascript import axios from 'axios'; axios.post('/upload-endpoint', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => console.log(response)) .catch(error => console.error(error)); ``` 此代码片段展示了怎样配置 Axios 请求头以便正确解析 `form-data` 类型的内容,并指定了目标 URL `/upload-endpoint` 用于接收这些数据。 对于更复杂的场景比如自定义上传行为,则可以通过 el-upload 组件提供的 `custom-request` 属性来进行更加灵活的操作[^2]。这允许开发者完全控制整个上传过程而不仅仅是简单的设置一些选项而已。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值