'very basic web application error in express
hello this is my first post. I'm a beginner of coding, so i watching video of opentutorials.org/course/2136/11950
i tried to find error in my code. but i can't not TT
When we enter site, it shows data lists. [localhost:3000/topic] enter image description here
and click the list, it shows description. like this. enter image description here
but in my case.. every text makes li... how can i do? enter image description here
//app.js
const express = require('express'); //가져오기
const bodyParser = require('body-parser');//가져오기
const fs = require('fs');
const { title } = require('process');
const app = express();
app.use(bodyParser.urlencoded({extended:false})); //bodyParser를 사용하겠다.
app.locals.pretty = true;
app.set('views', './views') //템플릿엔진 위치 설정
app.set('view engine', 'pug')//어떤 엔진사용할건지 설정
app.get('/topic/new', (req, res) => res.render('new') );
app.get('/topic', (req, res) => {
fs.readdir('data',(err, data) => {
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
res.render('view', {topics : data}); //사용자가 topic에들어오면 글목록보이기
})
} );
app.get('/topic/:id',(req, res)=>{
const id = req.params.id;
fs.readdir('data',(err, data)=>{
if(err){
res.status(500).send('Internal Server Error');
}
})
fs.readFile('data/'+id, 'utf8', (err, data) =>{
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
res.render('view',{title:id, topics : data, description:data });
})
})
//바뀌는정보를 콜론+변수명
app.post('/topic',(req, res) =>
{
const title = req.body.title;
const description = req.body.description;
//파일을 쓰게하기
fs.writeFile('data/'+title, description,(err)=> { //data폴더에 title로 파일명, 내용은 description
if(err){//에러가 있다면
res.status(500).send('Internal Server Error');
}
res.send('Success!')
});
});
app.listen(3000, () => { console.log('connected 3000 port!')}) //port, 콜백(서버연결시 출력)
//view.pug
doctype html
html(lang="en")
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 Document
body
h1 Server Side JavaScript
ul
each topic in topics
li
a(href="/topic/"+topic)= topic
article
h2= title
Solution 1:[1]
The render variable in app.get('/topic/:id') is incorrectly set. The below changes should render your view properly
app.get('/topic/:id',(req, res)=>{
const id = req.params.id;
let filesList = null
fs.readdir('data',(err, data)=>{
if(err){
res.status(500).send('Internal Server Error');
}
// This variable should be returned for topics
filesList = data
})
fs.readFile('data/'+id, 'utf8', (err, data) =>{
if(err){//??? ???
res.status(500).send('Internal Server Error');
}
// Update the topics variable
res.render('view',{title:id, topics : filesList, description:data });
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Singh3y |
