Why does this code work seamlessly on an HTML page when retrieving data from my hard drive, but as soon as I incorporate it into express and node, I encounter a
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
, even though the code is perfectly formatted. I've checked it with a formatter and manually created a json object. Below is the code snippet:
<html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Untitled</title>
</head>
<body>
<div id="output"></div>
<button id="getProperty">Get Property</button>
<script>
document.getElementById('getProperty').addEventListener('click', getProperty);
function getProperty() {
fetch('2016-regular.json')
.then((res) => res.json())
.then((data) => {
let output = '<h2>Property</h2>';
console.log(data);
data.propertystandings.propertystandingsentry.forEach(function(propertyEntry){
output += `
<ul>
<li>id: ${propertyEntry.property.ID}</li>
<li>city: ${propertyEntry.property.City}</li>
<li>prop name: ${propertyEntry.property.Name}</li>
<li>prop name: ${propertyEntry.rank}</li>
</ul>
`;
});
document.getElementById('output').innerHTML = output;
})
}
</script>
</body>
</html>
</html>
</html>
The same code that worked flawlessly in plain HTML now generates errors within Express:<br> **"index.ejs"**
<div id="output"></div>
<button id="getProperty">Get Property</button>
<script>
document.getElementById('getProperty').addEventListener('click', getProperty);
function getProperty() {
fetch("2016-regular.json")
.then((res) => res.json())
.then((data) => {
console.log(data);//**won't even read the data without that error**
});
}
</script>
**Express Code**
var express = require('express');
// var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
app.use(bodyParser());
app.use(cors());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function (request, response) {
response.render('index.ejs');
});
app.listen(8000, function() {
console.log('running on 8000');
});
Can you shed some light on why this setup functions smoothly in regular HTML when pulling data locally or when the file is manually saved, yet encounters the SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data issue once integrated into Express or when accessing the final API source for this data retrieval?