我正在尝试使用axios创建一个注册操作。当我提交时,我得到状态码为400的请求失败错误。我不知道我做错了什么。有人能帮忙吗?
这是我的操作代码:
export const userRegister = (
firstName,
lastName,
phone,
email,
password,
role,
username
) => {
return async (dispatch) => {
const config = {
headers: {
'Content-Type': 'application/json',
},
}
try {
const res = await axios.post(
`http://localhost:8000/api/v1/register`,
{ firstName, lastName, phone, email, password, role, username },
config
)
console.log(res)
// localStorage.setItem('token', res.data.token)
dispatch({
type: REGISTER_SUCCESS,
payload: {
successMessage: res.data.message,
token: res.data.token,
},
})
} catch (error) {
console.log(error.response)
dispatch({
type: REGISTER_FAIL,
payload: {
error: error.response.data,
},
})
}
}
}
我得到错误
Error: Request failed with status code 400
at createError (createError.js:16:1)
我的寄存器代码是:
const handleSubmit = async (e) => {
e.preventDefault()
dispatch(
userRegister(
firstName,
lastName,
phone,
email,
password,
role,
username
)
}
我做错了什么?
我建议您看一下以下内容:
API期望如何交付数据?
通常是Form DataJSON body。据我所知,您需要以JSON格式发送请求正文,而不是表单数据。这样的误解通常会导致error 400 Bad Request
,所以很可能您以错误的方式向API发送数据
也许你可以试试:
const res = await axios.post(
`http://localhost:8000/api/v1/register`,
{
firstName: firstName,
lastName: lastName,
...
},
config
)
*/这是一种更简洁的发送JSON正文的方式
参考:https://masteringjs.io/tutorials/axios/post
如果API需要处理表单数据,将配置属性从application/json
更改为Content-Type:'multipart/form-data'
,并使用new FormData()
构造函数发送表单数据