Skip to content

Instantly share code, notes, and snippets.

@king-panda
Last active June 17, 2020 12:09
Show Gist options
  • Save king-panda/9c8f68eaa95c009c58fdd37ad280cbd7 to your computer and use it in GitHub Desktop.
Save king-panda/9c8f68eaa95c009c58fdd37ad280cbd7 to your computer and use it in GitHub Desktop.
【Firebase】Cloud Functions + Express + EJSで動的コンテンツを配信する ref: http://qiita.com/kingpanda/items/aa9bdef2706857720058
├── firebase.json
├── functions
│   ├── firebase-debug.log
│   ├── index.js
│   ├── node_modules
│   │   ├── @types
│   │   ├── ・・・・・・・
│     │     ├── ・・・・・・・
│   ├── package-lock.json
│   ├── package.json
│   └── views
│   └── template.ejs
└── public
└── index.html
$ npm install express --save
if(routes[url_parts.pathname] == null){
res.status(404).send("page not found");
}else{
res.status(200).render("template",
{
title: routes[url_parts.pathname].title,
content: routes[url_parts.pathname].content
}
);
}
$ npm install ejs --save
app.set("view engine","ejs");
app.engine('ejs', require('ejs').__express);
const routes = {
"/page1":{
"title":"ページ1",
"content":"これはページ1です。"
},
"/page2":{
"title":"ページ2",
"content":"これはページ2です。"
}
};
const url = require('url');
const url_parts = url.parse(req.path);
{
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/**",
"function": "sample"
}
]
}
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="content-type">
<title>トップページ</title>
<style>
h1 { font-size:18px; background-color:#eaeaea; }
</style>
</head>
<body>
<header>
<h1 id="h1">トップページ</h1>
</header>
<div>
<p>これはトップページです。</p>
<ul>
<li><a href="/page1">ページ1へ</a></li>
<li><a href="/page2">ページ2へ</a></li>
</ul>
</div>
</body>
</html>
const functions = require('firebase-functions');
const express = require('express');
const url = require('url');
const app = express();
const routes = {
"/page1":{
"title":"ページ1",
"content":"これはページ1です。"
},
"/page2":{
"title":"ページ2",
"content":"これはページ2です。"
}
};
app.set("view engine","ejs");
app.engine('ejs', require('ejs').__express);
app.get("*",function(req,res){
const url_parts = url.parse(req.path);
if(routes[url_parts.pathname] == null){
res.status(404).send("page not found");
}else{
res.status(200).render("template",
{
title: routes[url_parts.pathname].title,
content: routes[url_parts.pathname].content
}
);
}
});
exports.sample = functions.https.onRequest(app);
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="content-type">
<title><%=title %></title>
<style>
h1 { font-size:18px; background-color:#eaeaea; }
</style>
</head>
<body>
<header>
<h1 id="h1"><%=title %></h1>
</header>
<div>
<p><%-content %></p>
<ul>
<li><a href="/">トップページへ</a></li>
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment