【发布时间】: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