In response to the use of Promise return ctx.body, received '404 Not Found'. But my mongodb is showing that the data was written. This troubled me, look forward to help.
router.get('/api/login', function *(next) {
let request = this.request;
let response = this.response;
let params = request.query;
userInfo.set({
document: {
user: params.name,
password: params.password
}
})
.then(res => {
response.body = {
code: 0,
data: {
uid: res.uid,
}
};
})
.catch(err => {
response.body = {
code: 999999,
error: err
}
})
yield next;
})
Here is the correct route:
router.get('/api/login', function *(next) {
let request = this.request;
let response = this.response;
let params = request.query;
yield userInfo.set({
document: {
user: params.name,
password: params.password
}
})
.then(res => {
response.body = {
code: 0,
data: {
uid: res.uid,
}
};
})
.catch(err => {
response.body = {
code: 999999,
error: err
}
})
})
I'd personally suggest something like this:
try {
this.body = yield userInfo.set({ ... })
} catch (error) {
this.status = xxx
this.body = { error }
}
Or omitting the try/catch portion and unifying your error-handling in middleware "upstream".
@PlasmaPower Great solution. I just found the generator with the promise of the callback usage. My understanding is that when using promise only, the request will end prematurely and return an error. So need to use the yield breakpoint, waiting for data to return. Do not know whether this understanding is correct.
Exactly. I'd also recommend you use tj's code, I was just showing the basic flaw.
@tj Very good program, I just started to encounter a callback nightmare. More fun
@PlasmaPower good call, hard to learn without seeing what the bug actually was :D
I'm going to start a wiki page on common problems. 404s in Koa can often be troublesome to troubleshoot.
static like(ctx){
const {unionId,topicId} = ctx.request.body
console.log(unionId);
LikeModel.findOrCreate({
where:{topicId},
defaults:{
unionId,topicId
}
// attributes: { exclude: ['id'] }
}).spread(async (data,created)=>{
if(created){
ctx.body={mes:'success'}
}else{
console.log(23232)
await LikeModel.destroy({
where:{topicId}
}).then((res)=>{
console.log(res) //it works
//below code doesn't why
ctx.status = 200
ctx.body = {mes:'fail'}
})
}
})
just the last
ctx.status = 200
ctx.body = {mes:'fail'}
do not works
@tj
Most helpful comment
I'd personally suggest something like this:
Or omitting the try/catch portion and unifying your error-handling in middleware "upstream".