Search code examples
javascriptnode.jstypescriptkoakoa-router

404s for every Koa route (Typescript)


Problem
  • Setting up Auth Controllers
  • Using Bcrypt and JWT
  • All POST Calls to Koa 404ing
  • Calls to other routes working fine
  • Possibly a issue with scope of code.
import * as Router from 'koa-router';
import * as bcrypt from 'bcrypt';
import User from '../models/user';

const router: Router = new Router();

/**
 * Signup new Users
 */

router.post('/signup', async ctx => {
    const { username, password, email } = ctx.request.body;
    bcrypt.hash(password, 10, (err, hash) => {
        if (err) {
            ctx.status = 500;
        } else {
            const user = new User({
                username,
                password: hash,
                email,
            });

            user.save()
                .then(result => {
                    ctx.status = 201;
                })
                .catch(err => {
                    if (err) {
                        ctx.response.status = 500;
                    }
                });
        }
    });
});

/**
 * Log in users
 */

router.post('/login', async ctx => {
    const { email, password } = ctx.request.body;
    User.findOne({ email }, (err, user) => {
        if (err) {
            ctx.status = 401;
            ctx.body = 'Auth Failed.';
        }
        bcrypt.compare(user.password, password, (err, result) => {
            if (err) {
                ctx.status = 401;
                ctx.body = 'Auth Failed.';
            }
            if (result) {
                ctx.status = 200;
                ctx.body = 'Auth Successful';
            } else {
                ctx.status = 401;
                ctx.body = 'Auth Failed';
            }
        });
    });
});

export default router;

I am not struggling to generate passwords or save users to the DB and I am receiving data into the server from the controllers the only thing is my server is not sending back anything but a 404 error.

import * as Koa from 'koa';
import * as dotenv from 'dotenv';
import * as mongoose from 'mongoose';
import * as cors from '@koa/cors';
import * as bodyParser from 'koa-body';
import bookRouter from './routes/book';
import userRouter from './routes/user';
dotenv.config();

const app: Koa = new Koa();

mongoose.connect(process.env.MGO_URI, { useNewUrlParser: true }).catch(error => {
    console.log(error);
    console.log('\n application shutting down for safety \n');
    process.exit(1);
});

// application wide middleware
app.use(cors());
app.use(bodyParser());

// application routes
app.use(userRouter.routes());
app.use(bookRouter.routes());

app.listen(3000);
console.log('Server running on port 3000');

Solution

  • First off, if you are using an async request handler you should use await. It makes the code a lot cleaner. I think this should work (although I'm not positive if bcrypt return a promise, but I think it does), for example:

    router.post('/signup', async ctx => {
      const { username, password, email } = ctx.request.body;
      try {
        let hash = await bcrypt.hash(password, 10);
        const user = new User({ username, password: hash, email });
    
        await user.save();
        ctx.status = 201;
      } catch(err) {
        console.log(err); // TODO: handle err
        ctx.status = 500;
      }
    });