我试图让我的服务器拒绝signup请求,如果用户试图注册一个现有的帐户。但是,我似乎不能正确地拒绝它,并将错误消息传递到我的客户端。第一个从我的reduxdev工具中,我的signup仍然被满足,即使我从我的服务器中拒绝了它。而且,我的服务器在一次尝试后崩溃,这让我怀疑有一个未捕获的错误。
signup
2j4z5cfb1#
客户端只接收您使用res.send()或next(err)执行的操作,然后next(err)将调用res.send()。承诺只在服务器本地执行,而不会被发送回客户端。在你的原始代码中,我建议你只使用基于承诺的异步操作,然后你可以在你的代码中使用throw,有一个地方来捕捉所有的错误,然后从那里将错误发送回客户端。
res.send()
next(err)
throw
class ServerError extends Error { constructor(msg, status) { super(msg) this.status = status; } } app.post('/signup', (req, res) => { try { const email = req.body.email const plainTextPassword = req.body.password; //check if user already exists const existingUser = await User.find({ email: email }); //account doesnt exist if (existingUser.length !== 0) { throw new ServerError('Account already exist', 403); } const hash = await bcrypt.hash(plainTextPassword, saltRounds); const user = new User({ email: email, password: hash }); const result = await user.save(); res.send(result); } catch (e) { if (!e.status) e.status = 500; console.log(e); res.status(e.status).send({err: e.message}); } });
然后,在使用fetch()的客户机代码中,需要检查result.ok,查看是否返回了2xx状态。fetch()仅在与目标主机的网络连接失败时才会拒绝。如果连接成功,即使它返回错误状态,fetch()承诺将得到解决。您必须检查result.ok以查看是否得到了2xx状态。
fetch()
result.ok
//reduxSlice.js export const signup = createAsyncThunk( 'userAuth/signup', async (payload, thunkAPI) => { const { email, password } = payload try { const result = await fetch( signupPath, { mode: 'cors', credentials: 'include', method: "post", body: JSON.stringify({ email, password }), headers: { 'Content-Type': 'application/json' } }); // check to see if we got a 2xx status success if (!result.ok) { throw new Error(`signup failed: ${response.status}`); } return result.json() } catch (error) { console.log(error) //this line executes } } )
1条答案
按热度按时间2j4z5cfb1#
客户端只接收您使用
res.send()
或next(err)
执行的操作,然后next(err)
将调用res.send()
。承诺只在服务器本地执行,而不会被发送回客户端。在你的原始代码中,我建议你只使用基于承诺的异步操作,然后你可以在你的代码中使用
throw
,有一个地方来捕捉所有的错误,然后从那里将错误发送回客户端。然后,在使用
fetch()
的客户机代码中,需要检查result.ok
,查看是否返回了2xx状态。fetch()
仅在与目标主机的网络连接失败时才会拒绝。如果连接成功,即使它返回错误状态,fetch()
承诺将得到解决。您必须检查result.ok
以查看是否得到了2xx状态。