【问题标题】:Request payload is transformed to query params after POST request请求有效负载在 POST 请求后转换为查询参数
【发布时间】:2021-02-12 16:02:42
【问题描述】:

我有一个 React 应用程序,我在其中使用 axios 将表单数据发送到服务器。

我能够发送数据并且数据库也已更新。问题是,在发送请求后,表单中的数据会附加到url,就好像我在传递查询参数一样。

这是带有表单的组件

import React from 'react'
import axios from '../../axios'

function HomePage(props) {
    const [name, setName] = React.useState('')
    const [email, setEmail] = React.useState('')
    const [password, setPassword] = React.useState('')

    const handleChange = (event) => {
        switch(event.target.name) {
            case "name":
                setName(event.target.value)
                break
            case "email":
                setEmail(event.target.value)
                break
            case "password":
                setPassword(event.target.value)
                break
            default:
                break
        }
    }

    const validation = () => {
        let isValid = true
        return isValid
    }

    const handleSubmit = () => {
        if(validation()) {
            let data = {
                name: name,
                email: email,
                password: password
            }

            axios.post('/user/create-user', data)
                .then(response => {
                    console.log(response)
                })
                .catch(error => {
                        console.log(error)
                    })
        }
    }

    return (
        <div>
            <form>
                <input 
                    type="text" 
                    required
                    name="name" 
                    value={name} 
                    onChange={handleChange}/>
                <input 
                    type="email" 
                    required
                    name="email" 
                    value={email} 
                    onChange={handleChange}/>
                <input 
                    type="password" 
                    required
                    name="password" 
                    value={password} 
                    onChange={handleChange}/>
                <button 
                    type="submit" 
                    onClick={handleSubmit}>Submit</button>
            </form>
        </div>
    )
}

export default HomePage

点击提交按钮后,我在浏览器中看到带有表单数据的url

我还可以在dev tools 中看到状态(已取消)。

我认为浏览器正在导航到带有查询参数的新 url,我不知道为什么。这不仅仅是在 Chrome 中。

控制台以蓝色显示“导航到”,其中包含带有查询参数的不需要的路由。

任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    表单元素默认使用GET作为action,而且你在提交时没有使用preventDefault,所以默认情况下表单会发出get请求。

    在表单标签上添加表单属性method="post", 并将e.preventDefault() 添加到handleSubmit

    一些参考资料 Forms in react, Handling events

    【讨论】:

    • 我想你的意思是,method="post",谢谢它成功了。
    猜你喜欢
    • 1970-01-01
    • 2015-09-04
    • 2013-09-23
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多