【发布时间】:2019-07-19 07:11:59
【问题描述】:
问题
- 设置身份验证控制器
- 使用 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');
【问题讨论】:
标签: javascript node.js typescript koa koa-router