【问题标题】:Why is my axios post request not sending data? I'm getting a response that means the fields are empty为什么我的 axios post 请求没有发送数据?我收到了表示字段为空的响应
【发布时间】:2021-06-03 01:20:31
【问题描述】:

我不知道为什么数据没有发送到后端。

当我在 Insomnia 上测试 API 时,它运行良好。我什至使用 API 向数据库添加了新用户,但是当我尝试使用 redux 和 axios 从 react 添加新用户时,它没有执行,而是收到一条回复说字段不能为空。

我已尝试控制台记录我发送的所有数据,并且所有字段都已正确填充。我不知道我做错了什么。

我使用 express-validator 来检查输入以及正常的错误处理,这就是为什么我得到响应为空的原因。

这是我的代码 在 redux 中发送数据

export const signin = data => dispatch => {

    const config = {
        method : "post",
        url : "http://localhost:5000/user/signin",
        headers : {
            "Content-Type":"application/json"
        },
        body : JSON.stringify(data)
    }

    console.log(config.body)

    axios(config)
    .then(res => dispatch({
        type : LOGIN_SUCCESS,
        payload : res.data
    }))
    .catch(err => {
        dispatch(error_msg(err.response.data, err.response.status))
        dispatch({
            type : LOGIN_FAIL
        })
    })
}

反应表单组件

import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import AuthLayout from './AuthLayout'
import Layout from './Layout'
import {connect} from 'react-redux'
import {signin} from '../store/actions/authAction'
import axios from 'axios'

function SignIn({signin}) {

    const [value, setValue] = useState({
        email : '',
        password : ''
    })

    const handleChange = (e) => {
        setValue({
            ...value,
            [e.target.name] : e.target.value
        })
    }

    const handleSubmit = e => {
        e.preventDefault()

        const {email, password} = value

        const oldUser = {
            email,
            password
        }

        axios({method : "post",
        url : "http://localhost:5000/user/signin",
        headers : {
            "Content-Type":"application/json; charset=UTF-8",
            "Accept":"Token",
            "Access-Control-Allow-Orgin":"*",
        },
        body : JSON.stringify(oldUser)})
        .then(res => console.log(res.data))
        .catch(err => console.log(err.response.data))
        
    }

    return (
       <AuthLayout>
          <div className="form_container" style={bg}>
            <div className="form_title">
                <h2>Sign In</h2>
                
            </div>
            <form onSubmit={handleSubmit}>
                <div className="form_div">
                    <input type="text" placeholder="Enter Email" name="email" value={value.email} onChange={handleChange} />
                </div>
                <div className="form_div">
                    <input type="number" placeholder="Enter Password" name="password" value={value.password} onChange={handleChange} />
                </div>
                <div className="form_div form_btn">
                    <button>Submit</button>
                </div>
                <div className="form_div checkbox">
                    <input type="checkbox" />
                    <h4>Remember me</h4>
                </div>
            </form>
                <p>Don't have an account? <Link to="/signup"><span>Sign up</span></Link> </p>
                
          </div>
       </AuthLayout>
    )
}

const bg = {
    backgroundImage: 'url(image/Group1.svg)'
}

const mapStateToProps = state => {

    return{
        user : state.auth.user
    }
}



export default connect(mapStateToProps, {signin})(SignIn)

我没有包括后端,因为它工作得很好。

【问题讨论】:

    标签: javascript reactjs react-redux axios


    【解决方案1】:

    这个应该改成fetch,

    axios.post('url', 'body', 'headers')
    

    以上是应该使用的axios的实际结构。

    试试上面的。

    【讨论】:

      【解决方案2】:

      这里不需要JSON.stringify

      body : JSON.stringify(data),
      

      使用

      body: data,
      

      因为数据本身是在 axious 中被字符串化的,如果你给它提供已经被字符串化的数据,你会有额外的转义 json,不能被认为是有效的 json 作为后端服务器

      【讨论】:

        【解决方案3】:

        感谢所有帮助我理解问题的人,感谢您的所有努力。

        我尝试了这里提供给我的一些解决方案,但没有奏效。

        所以我后来做的是删除 body 变量并用配置对象中的数据替换它,它开始工作了。

        这是代码:

        export const signin = data => dispatch => {
        
            const config = {
                method : "post",
                url : "http://localhost:5000/user/signin",
                headers : {
                    "Content-Type":"application/json",  
                },
                data : JSON.stringify(data)
            }
        
            console.log(config.data)
        
            axios(config)
            .then(res => dispatch({
                type : LOGIN_SUCCESS,
                payload : res.data
            }))
            .catch(err => {
                dispatch(error_msg(err.response.data, err.response.status))
                dispatch({
                    type : LOGIN_FAIL
                })
            })
        }
        

        我不认为这是最好的解决方案,但在这种情况下,它对我有用。

        【讨论】:

          猜你喜欢
          • 2020-01-07
          • 2019-08-30
          • 2020-04-29
          • 1970-01-01
          • 2018-03-27
          • 2019-09-11
          • 2021-11-16
          • 1970-01-01
          • 2021-11-19
          相关资源
          最近更新 更多