Vue使用axios用post方式将表单中的数据以json格式提交给后端接收

本文介绍如何在Vue应用中利用axios通过POST方式将表单数据以JSON格式发送给后端。以登录注册功能为例,阐述了在Vue data中定义表单数据对象,使用v-model绑定输入字段,并在axios.post请求中正确传递JSON数据的方法。
摘要由CSDN通过智能技术生成

Vue Axios Post Json

实现步骤:以登录注册功能为例

1.后端controller层代码代码

我采用的接收形式数据是json格式

    @PostMapping("/login")
    public Resp login(@RequestBody User user){
   
        User login = userService.login(user.getStudentid(),user.getPassword());
        return Resp.success(login);
    }
    @PostMapping("/regist")
    public Resp regist(@RequestBody User user){
   
        userService.regist(user);
        return Resp.success(null)
  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 表单数据JSON 格式传递给 POST 类型的接口,你可以按照以下步骤进行操作: 1. 创建一个表单对象:使用 Vue数据绑定功能,在 data 属性创建一个对象来存储表单数据。 ```vue <template> <form @submit="submitForm"> <input v-model="formData.username" type="text" name="username" /> <input v-model="formData.password" type="password" name="password" /> <input v-model="formData.email" type="email" name="email" /> <button type="submit">提交</button> </form> </template> <script> export default { data() { return { formData: { username: '', password: '', email: '' } }; }, methods: { submitForm() { // 在这里处理表单提交 } } }; </script> ``` 2. 在 submitForm 方法,将表单数据转换为 JSON 字符串并发送 POST 请求。 ```vue <script> import axios from 'axios'; export default { // ... methods: { submitForm() { const jsonFormData = JSON.stringify(this.formData); // 发起 POST 请求 axios.post('https://example.com/api/endpoint', jsonFormData, { headers: { 'Content-Type': 'application/json' } }) .then(response => { // 处理成功响应 console.log(response.data); }) .catch(error => { // 处理请求错误 console.error(error); }); } } }; </script> ``` 在上述代码,我们使用axios 库来发起异步请求。在发送 POST 请求时,我们将 JSON 字符串作为请求主体,并设置请求头的 Content-Type 为 application/json。 确保将实际的接口 URL 替换为你要发送请求的后端接口地址。 这样,Vue 将会将表单数据JSON 格式传递给 POST 类型的接口。在后端接口,你可以根据接口定义解析 JSON 数据并进行相应的处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值