如何使用deno oak 同时作为api服务器和web服务器
首先我们作为api服务器,动态路由
const router = new Router();
router
.get("/", (context) => {
context.response.body = `Hello world! ${moment().format("YYYY-MM-DD")}`;
})
.get("/s/:urlid", (context) => {
const urls = JSON.parse(Deno.readTextFileSync("./urls.json"));
if (context.params && context.params.urlid && urls[context.params.urlid]) {
if (
urls[context.params.urlid].expiryDate > moment().format("YYYY-MM-DD")
) {
context.response.redirect(urls[context.params.urlid].dest);
} else {
context.response.body = "Link Expired";
}
} else {
context.response.body = "404";
}
});
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
console.log("> Listening on http://localhost:8000");
await app.listen({ port: 8000 });
console.log("REEEEEE")
其次我们把deno oak作为静态资源web服务器
const app = new Application();
// static content
app.use(async (context, next) => {
await send(context, context.request.url.pathname, {
root: `${Deno.cwd()}/static`,
index: "index.html",
});
})
console.log("> Listening on http://localhost:8000");
await app.listen({ port: 8000 });
console.log("REEEEEE")
如何同时作为动态路由,和静态资源
我们使用next函数,来达到这个目的。
好处是开发网页,不需要使用mvc架构,直接使用api+网页的形式。
```javascript
const router = new Router();
router
.get("/", (context) => {
context.response.body = `Hello world! ${moment().format("YYYY-MM-DD")}`;
})
.get("/s/:urlid", (context) => {
const urls = JSON.parse(Deno.readTextFileSync("./urls.json"));
if (context.params && context.params.urlid && urls[context.params.urlid]) {
if (
urls[context.params.urlid].expiryDate > moment().format("YYYY-MM-DD")
) {
context.response.redirect(urls[context.params.urlid].dest);
} else {
context.response.body = "Link Expired";
}
} else {
context.response.body = "404";
}
});
const app = new Application();
// error handler
app.use(async (context, next) => {
try {
await next()
} catch (err) {
console.log(err)
}
})
app.use(router.routes());
app.use(router.allowedMethods());
// static content
app.use(async (context, next) => {
try {
await send(context, context.request.url.pathname, {
root: `${Deno.cwd()}/static`,
index: "index.html",
});
} catch {
next()
}
})
console.log("> Listening on http://localhost:8000");
await app.listen({ port: 8000 });
console.log("REEEEEE")