代码拉取完成,页面将自动刷新
const Koa = require("koa");
const { bodyParser } = require("@koa/bodyparser");
const service = require("./service");
const loadConfig = require("./config/configLoader");
const config = loadConfig();
const app = new Koa();
app.use(async (ctx, next) => {
if (ctx.request.url !== "/translate") {
ctx.response.status = 404;
ctx.body = "error url, only /translate is provided";
return;
}
if (ctx.request.method !== "POST") {
ctx.status = 405;
ctx.body = "error method, only POST is provided";
return;
}
await next();
});
app.use(
bodyParser({
enableTypes: ["json"],
onError(err, ctx) {
ctx.throw(422, "error body type, should be json");
}
})
);
app.use(async (ctx, next) => {
const validationResult = await service.validateRequestBody(ctx);
if (validationResult.isValid) {
await next();
} else {
ctx.status = 400;
ctx.body = { message: validationResult.error };
}
});
app.use(async (ctx) => {
const result = await service.translate(ctx.request.body);
ctx.status = 200;
ctx.response.type = "application/json";
ctx.response.body = result;
});
const PORT = config.PORT;
app.listen(PORT, () => {
console.log("server is running at http://localhost:" + PORT);
});
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。