Reputation: 301
I'm very new to Express and nodeJS.
I'm working around with query string and dynamic web page and it says that cannot get id.
I have no idea where I did go wrong.
Any help would be appreciated!
const express = require('express');
const app = express();
const port = 3000;
const fs = require('fs');
app.get('/', (req, res) => {
fs.readdir('./data', (err, list) => {
fs.readFile(`data/${req.query.id}`, 'utf8', (err, data)=>{
if(!req.query.id){
req.query.id = "Welcome";
data = "Hello World";
}
res.send(`<html>
<head></head>
<body>
<h1><a href="#">Web<a></h1>
<ul>
${list.map(item=>`<li><a href="/id?=${item}">${item}</a></li>`).join('')}
</ul>
<a href="create">Create</a>
<h2>${req.query.id}</h2>
<p>${data}</p>
</body>
</html>`)
})
})
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Upvotes: 0
Views: 398
Reputation: 89
Probably you are calling url like "/id" and you are trying get a query string. For get id as variable on url, you must put on path like:
app.get("/:id", (req, res) => {
const id = req.params.id;
})
If you want get a query string, use:
app.get("/", (req, res) => {
const id = req.query.id;
})
You need call url like: /?id=1
Upvotes: 2