const fs = require('fs');
const http = require('http');
const url = require('url');
const data = fs.readFileSync('starter/templates/template-overview.html', 'utf-8');
const tempOverview = fs.readFileSync('starter/templates/template-card.html', 'utf-8');
const tempCard = fs.readFileSync('starter/templates/template-product.html', 'utf-8');
const tempProduct = fs.readFileSync('starter/dev-data/data.json', 'utf-8');
const dataObj = JSON.parse(data);
const server = http.createServer((req, res) => {
const pathName = req.url;
//Overview page
if (pathName === '/' || pathName === '/overview') {
res.writeHead(200, { 'Content-type': 'text/html' });
res.end(tempOverview);
//Product page
} else if (pathName === '/product') {
res.end('This is our products:)');
//Api
} else if (pathName === '/api') {
res.writeHead(200, {
'Content-type': 'application/json'
});
res.end(data);
}
//not found page
else {
res.writeHead(404, {
'Content-type': 'text/html',
'My-own-header': 'Hello client'
});
res.end('<h1>Page not found</h1>');
}
});
//127.0.0.1 locall host ip
server.listen(8000, '127.0.0.1', () => {
console.log('The server is listening');
});
this is the code and when i start the nodejs server it gives me this syntax error i am still a beginner so it might be a stupid error i don`t know
i expected it to run in the site but it gives me that error
>Solution :
You have this line
const data = fs.readFileSync('starter/templates/template-overview.html', 'utf-8');
Where you are reading the file contents of an HTML file and saving it to a variable called data.
Then you have this line
const dataObj = JSON.parse(data);
Where you are trying to parse the HTML data as JSON data, and that’s why you have the error. It saying it was expecting JSON data but it is running into data that isn’t JSON.