Last active
February 9, 2021 12:29
-
-
Save shalaby/25c3b816f2084e8cd4e2274d8bf564ea to your computer and use it in GitHub Desktop.
Simple blog server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const app = express() | |
const bodyParser = require('body-parser') | |
app.use(bodyParser.urlencoded({ extended: true })) | |
const posts = [] | |
app.get('/', function (req, res) { | |
const postsHtml = posts.map(function (post) { | |
return ` | |
<div> | |
<h3>${post.title}</h3> | |
<p>${post.content}</p> | |
</div> | |
` | |
}) | |
const content = ` | |
<h2>مدونتي الجميلة</h2> | |
${postsHtml.join('')} | |
` | |
const page = getHeader() + content + getFooter() | |
res.send(page) | |
}) | |
app.get('/new', function (req, res) { | |
const content = ` | |
<h1>تدوينة جديدة</h1> | |
<form method="post" action="/save"> | |
<input placeholder="العنوان" name="title"> | |
<textarea placeholder="المحتوي" name="content"></textarea> | |
<button>إرسال</button> | |
</form> | |
` | |
const page = getHeader() + content + getFooter() | |
res.send(page) | |
}) | |
app.post('/save', function (req, res) { | |
const newPostTitle = req.body.title | |
const newPostContent = req.body.content | |
const newPost = { | |
title: newPostTitle, | |
content: newPostContent | |
} | |
posts.push(newPost) | |
res.redirect('/') | |
}) | |
function getHeader() { | |
return ` | |
<!DOCTYPE html> | |
<html lang="ar" dir="rtl"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>مدونتي الجميلة</title> | |
<style> | |
body { | |
background-color: #eee; | |
align-text: center | |
} | |
div { | |
background-color: white; | |
margin: 16px; | |
padding: 16px | |
} | |
input, textarea { | |
display: block; | |
margin-bottom: 8px; | |
width: 200px | |
} | |
</style> | |
</head> | |
<body> | |
` | |
} | |
function getFooter() { | |
return ` | |
</body> | |
</html> | |
` | |
} | |
app.listen(3000, function () { | |
console.log('Server is running ...') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment