[英]404s for every Koa route (Typescript)
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');
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. 我并没有努力生成密码或将用户保存到数据库,我正在从控制器将数据接收到服务器中,唯一的问题是我的服务器除了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');
First off, if you are using an async
request handler you should use await
. 首先,如果您使用的是async
请求处理程序,则应使用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: 我认为这应该可行(尽管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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.