Browse Source

HA05: new JSON Datei (blog.json), new Routes to Save BlogDatas in blog.json

master
lauraF 3 years ago
parent
commit
2bf8f88600
  1. 16
      public/models/blog.json
  2. 51
      routes/blog.js

16
public/models/blog.json

@ -0,0 +1,16 @@
[
{
"id": 1,
"title": "titel eins",
"username": "name",
"date": "2022-04-27",
"text": "text"
},
{
"id": 2,
"title": "nummer Zwei",
"username": "noch ein Name",
"date": "2022-05-04",
"text": "und noch ein Text"
}
]

51
routes/blog.js

@ -1,23 +1,52 @@
var express = require('express'); var express = require('express');
let res = require('express/lib/response'); let res = require('express/lib/response');
var router = express.Router(); var router = express.Router();
//fileStream ermöglicht Lesen und Schreiben auf Festplatte
var fs = require('fs');
let blog = [];
//let blog = [];
//erstellt JSONObjekt
let rawdata = fs.readFileSync('./public/models/blog.json');
//wandelt JSONObjekt in JsObjekt
let blogInhalt = JSON.parse(rawdata);
/* GET home page. */ /* GET home page. */
router.route('/') router.route('/')
.get((req, res, next) => { // => Pfeilfunktion: ersetzt function() .get((req, res, next) => { // => Pfeilfunktion: ersetzt function()
res.send({ blog });
for (i = 0; i < blogInhalt.length; i++){
console.log(blogInhalt[i].id, "." , blogInhalt[i].title);
}
res.send({ blogInhalt });
}) })
.post((req, res, next) => { .post((req, res, next) => {
let blogeintrag = [];
/*let blogeintrag = [];
let title = req.body.title; let title = req.body.title;
let username = req.body.username; let username = req.body.username;
let date = req.body.date; let date = req.body.date;
let text = req.body.text; let text = req.body.text;
console.log(title); console.log(title);
blogeintrag.push(title, username, date, text); blogeintrag.push(title, username, date, text);
blog.push(blogeintrag);
blog.push(blogeintrag); */
let blogeintrag = {
id : blogInhalt.length + 1,
title : req.body.title,
username : req.body.username,
date : req.body.date,
text : req.body.text
}
console.log(blogeintrag);
//hänge blogeintrag an blogInhalt
blogInhalt.push(blogeintrag);
let date = JSON.stringify(blogInhalt, null, 2);
fs.writeFileSync('./public/models/blog.json', date);
res.render('blogPost', { title: 'Nächster Post' }) res.render('blogPost', { title: 'Nächster Post' })
}); });
@ -25,11 +54,17 @@ router.get('/newPost', function (req, res, next) {
res.render('blogPost', { title: 'BlogEintrag' }); res.render('blogPost', { title: 'BlogEintrag' });
}); });
router.get('/:id', function (req, res, next) {
let blogID = req.params.id;
router.get('/:postID', function (req, res, next) {
let blogID = req.params.postID;
if(blogID > blogInhalt.length){
console.log("kein entsprechender Eintrag vorhanden");
res.send("kein entsprechender Eintrag vorhanden")
} else {
console.log(blogInhalt[blogID - 1]);
res.send(blogInhalt[blogID - 1]);
}
console.log(blogID);
res.send(blog[blogID]);
}); });
module.exports = router; module.exports = router;
Loading…
Cancel
Save