0
问题
  • 设置身份验证控制器
  • 使用 Bcrypt 和 JWT
  • 所有对 Koa 404ing 的 POST 调用
  • 呼叫其他路线正常
  • 可能是代码范围的问题。
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;

我没有努力生成密码或将用户保存到数据库,并且我正在从控制器将数据接收到服务器中,唯一的事情是我的服务器除了 404 错误之外没有发回任何内容。

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');
4

1 回答 1

0

首先,如果您使用的是async请求处理程序,您应该使用await. 它使代码更干净。我认为这应该可行(尽管如果返回承诺我不肯定bcrypt,但我认为确实如此),例如:

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;
  }
});
于 2019-02-26T20:32:56.330 回答