I'm failing to return my token
to actually be retrieved from my middlewares using xhr agents say supertest
and postman
. after I signup my user.
I'm trying to get the jwt from body so i can make authenticated requests, but for some reason i keep on getting "Not Found".
Please take a look at my code..
signup route
router.post('/signup', signUp);
What important about /signup
route, is if I add a middleware after signUp
I can access the ctx.response.body
passed from signUp
middleware but I can't publish it anyware. Or i don't know how.
and the signUp middleware
const signUp = async (ctx, next) => {
const bodyInfo = await ctx.request.body;
if(!bodyInfo.username || !bodyInfo.password) {
ctx.status = 402;
ctx.body = "Error, username and password must be provided!";
}
const userInst = new User(bodyInfo);
userInst.save(async(err, user) => {
if(err) { return next(err); }
const token = tokenForUser(user);
ctx.body = token;
return next();
});
};
export { signUp, signIn };
I should mention that this saved the data fine and when I check in the database the data is there, console.logs
of ctx.response.body
in a next middleware to signUp
shows the generated token too.
I test /signup with this code:
beforeEach(async () => {
a_user = { "username": "testing",
"password": 'newpassword',
"age": 22, "height": 179
};
await User.remove({});
})
afterEach(async () => await User.remove({}));
it('signs up', async () => {
await request(inst)
.post('/api/v1/signup')
.send(a_user)
.expect(200);
});
The full stack trace of my error is:
1) Authentication signs up:
Error: expected 200 "OK", got 404 "Not Found"
at Test._assertStatus (node_modules/supertest/lib/test.js:266:12)
at Test._assertFunction (node_modules/supertest/lib/test.js:281:11)
at Test.assert (node_modules/supertest/lib/test.js:171:18)
at assert (node_modules/supertest/lib/test.js:131:12)
at node_modules/supertest/lib/test.js:128:5
at Test.Request.callback (node_modules/superagent/lib/node/index.js:631:3)
at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/index.js:795:18)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Only in tests but using postman works fine. Is there something i'm not doing right?
I'm using koa: 2.0.0
, supertest: 2.0.1
and for routes koa-rest-router: 1.0.0
.
Please help! Thanks.
Sad, I didn't perform it in "The async/awaits way".
This
userInst.save(async(err, user) => {
if(err) { return next(err); }
const token = tokenForUser(user);
ctx.body = token;
return next();
});
Had to be
This
const user = await userInst.save();
const token = tokenForUser(user);
ctx.body = token;
return next()
I didn't put an await before userInst.save
, causing the function to return an instantly resolving promise.