Javascript 我在我的react和restapi应用程序中遇到一个错误,其中一个变量未定义
感谢您的时间如果您正在阅读本文,我正在使用react和rest api制作一个完整的堆栈应用程序,我遇到了如下错误:Javascript 我在我的react和restapi应用程序中遇到一个错误,其中一个变量未定义,javascript,reactjs,rest,undefined,react-fullstack,Javascript,Reactjs,Rest,Undefined,React Fullstack,感谢您的时间如果您正在阅读本文,我正在使用react和rest api制作一个完整的堆栈应用程序,我遇到了如下错误: TypeError: errors is undefined submit UserSignUp.js:53 promise callback*UserSignUp/this.submit UserSignUp.js:51 React 17 unstable_runWithPriority scheduler.development.js:653
TypeError: errors is undefined
submit UserSignUp.js:53
promise callback*UserSignUp/this.submit UserSignUp.js:51
React 17
unstable_runWithPriority scheduler.development.js:653
React 24
js index.js:8
Webpack 7
引发此错误的部分就在这里:
context.userController.createUser(user)
.then( errors => {
if (errors.length) {
this.setState( {errors});
} else {
context.actions.signIn(emailAddress,password)
.then( () => {this.props.history.push('/authenticated')} );
}
})
.catch( err => { // handle rejected promises
console.log(err);
this.props.history.push('/error'); // push to history stack
})
}
}
以下是我的createUser函数代码:
async createUser(user){
const response = await this.call_api('/users', 'POST', user);
if (response.status === 201) {
return [];
}
else if (response.status === 400) {
return response.json().then(data => {
return data.errors;
});
}
else {
throw new Error();
}
}
}
这是处理帖子/用户的代码
router.post('/users', asyncHandler(async (req, res, next) => {
const user = req.body;
if(user.password)
{
user.password = bcryptjs.hashSync(user.password);
};
try
{
await User.create(user);
res.status(201).location('/').end();
} catch (error) {
if (error.name === 'SequelizeValidationError' || error.name === 'SequelizeUniqueConstraintError')
{
const errorMsg = [];
error.errors.map((err) => errorMsg.push(err.message));
res.status(400).json({ error: errorMsg });
} else
{
next(error);
};
};
}));
我真的不确定我的错误变量在这里发生了什么,所以如果有人能帮助我,那就太好了。这是我的github链接:
您的
createUser
函数代码返回数据。如果响应状态不是201,则返回错误。但是您的API在error
键中发送错误。在API路由处理程序中更新errors
的键,您就可以开始了
res.status(400).json({errors:errorMsg});
你能用抛出错误的代码更新你的问题吗?@ArunKumarMohan我想这就是你的意思谢谢。您还可以添加createUser
函数代码吗?是的@ArunKumarMohan我把所有内容都放在那里,因为yaI是指UserController.js
中定义的createUser
函数。您能否将API代码处理请求共享给POST/users
@zakmosbacher?