Answer the question
In order to leave comments, you need to log in
How to send error to client in koa?
Everything is ok on the server. But the client gets 404 instead of 403. What am I doing wrong?
But yes:
router.post('/api/auth/sign-up', async (ctx, next) => {
const user = new UserModel({
['info.name']: ctx.request.body.username,
email: ctx.request.body.email,
password: ctx.request.body.password
});
user
.save()
.then(user => {
ctx.body = user;
})
.catch(err => {
ctx.throw(403, "Cannot create user or user is already created!");
});
await next();
});
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = {code: err.statusCode, message: err.message};
ctx.app.emit('error', err, ctx);
}
})
app.on('error', (err, ctx) => {
console.error(err);
});
app.use(router.routes());
handleSubmit = e => {
e.preventDefault();
if (this.validateForm() === true) {
axios
.post('/api/auth/sign-up', {
username: this.state.username,
email: this.state.email,
password: this.state.password
})
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
});
} else {
alert('incorrect data');
}
}
Answer the question
In order to leave comments, you need to log in
1) in the POST method, `await next()` is not needed at the end
, in principle, when you process the final paths, `next` is not needed, it is needed only for middleware, when you need to send the request further.
2) once you start working with async/await - work only with them, don't use promises
try {
await user.save()
ctx.body = user;
} catch (err) {
ctx.throw(403, "Cannot create user or user is already created!");
}
Probably the problem is that you do not know js , when you use promises in async functions, the result of their execution will be much later than await next... And it will not be important for the response to the client.
router.post('/api/auth/sign-up', async (ctx, next) => {
const user = new UserModel({
['info.name']: ctx.request.body.username,
email: ctx.request.body.email,
password: ctx.request.body.password
});
await user
.save()
.catch(err => {
ctx.throw(403, "Cannot create user or user is already created!");
});
ctx.body = user;
await next();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question