指導老師: [陳鍾誠]
先import deno 的oak套件
import { Application, Router, send } from "https://deno.land/x/oak/mod.ts";
使用他的Application建立伺服器
const app = new Application();
await app.listen({ port: 6020 });
使用他的router接收訊息或是把資料放到目錄裡面
以下是server範例
import { Application, Router, send } from "https://deno.land/x/oak/mod.ts";
const router = new Router();
// 使用router讓不同的路徑顯示不同資料
router
// 根目錄/,(.*)代表所有的符號都可以
.get("/(.*)", async (ctx) => {
await send(ctx, ctx.params[0],{
// 把資料夾(根目錄)的檔案傳到網站上
root: Deno.cwd(),
// 預設檔案(一進網站就會執行)
index: "index.html"
})
})
// 放到路徑/assets裡面
.get("/assets/(.*)", async (ctx) => { //get("/", func())根目錄顯示
await send(ctx, ctx.params[0],{
// 把資料夾(/assets)的檔案傳到網站上
root: Deno.cwd() + "/assets",
})
})
const app = new Application();
// router的所有方法都可以使用
app.use(router.allowedMethods());
// 讓router啟動
app.use(router.routes());
console.log('start at : http://127.0.0.1:6020')
// 把伺服器開在port 6020
await app.listen({ port: 6020 });
!!改了後端的東西就要重啟伺服器才可以運行!! (因為是在後端)
Router可以用ctx.params[0]和ctx.request.url.pathname,但是用App就只能用後者
import { Application, send } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
app.use(async (ctx) => {
console.log('path=', ctx.request.url.pathname)
await send(ctx, ctx.request.url.pathname, {
// root: `${Deno.cwd()}/public/`,
root: Deno.cwd()+'/public/',
index: "index.html",
});
});
console.log('start at : http://127.0.0.1:8000')
console.log('cwd=', Deno.cwd())
await app.listen({ port: 8000 });