Can anyone tell me why this code will work perfectly in an HTML page when accessing the data from my hard drive but when I add it to express and node I get a
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
with perfectly formatted code. I know I tested it with a formatter and I even manually created a json object. Here is the code:
<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>
But then this code in express causes the error- same exact file that worked perfectly before ran thru express now causes this error:
**"index.ejs"**
<div id="output"></div>
<button id="getProperty">Get Property</button>
<script>
document.getElementById('getProperty').addEventListener('click', getProperty);
function getProperty() {
/*fetch('sample.txt')
.then(function(res) {
return res.text();
})
.then(function(data){
console.log(data);
});*/
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');
});
any ideas why this works fine in plain html when accessing a folder or if I manually create and save the file on my hard drive but once I put it in express or try to access the API the data came from (the final goal) I get the error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Can anyone tell me why this code will work perfectly in an HTML page when accessing the data from my hard drive but when I add it to express and node I get a
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
with perfectly formatted code. I know I tested it with a formatter and I even manually created a json object. Here is the code:
<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>
But then this code in express causes the error- same exact file that worked perfectly before ran thru express now causes this error:
**"index.ejs"**
<div id="output"></div>
<button id="getProperty">Get Property</button>
<script>
document.getElementById('getProperty').addEventListener('click', getProperty);
function getProperty() {
/*fetch('sample.txt')
.then(function(res) {
return res.text();
})
.then(function(data){
console.log(data);
});*/
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');
});
any ideas why this works fine in plain html when accessing a folder or if I manually create and save the file on my hard drive but once I put it in express or try to access the API the data came from (the final goal) I get the error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Share Improve this question edited Nov 27, 2017 at 17:26 Paul T. 4,95212 gold badges47 silver badges63 bronze badges asked Nov 27, 2017 at 17:04 baryjones23saturnbaryjones23saturn 813 silver badges8 bronze badges 9- 2 We probably don't need that giant wall of code, and rather just the JSON itself – Dexygen Commented Nov 27, 2017 at 17:28
- I agree but there is nothing I can do to the way it is formatted because it is ing from an api. The api saves the data to the harddrive at work and then we read from that file. The data is fine I just think it is something with express or fetch. – baryjones23saturn Commented Nov 27, 2017 at 17:31
- Have you checked if your request for JSON is not failing? – Vivek Athalye Commented Nov 27, 2017 at 17:34
- it gets the same response. it fails. I can't even get the data object. BUT the exact same data object works fine by itself. I showed in the example just trying to access the data in the index.ejs file but the first file that works is the same thing same data and it accesses it fine from my hard drive. It's when it goes through express these errors e up. – baryjones23saturn Commented Nov 27, 2017 at 17:36
-
(1) what is the response (i.e.
console.log(res)
)? That should provide insight into the error being returned by the server. (2) Is your express app set up to serve the static resource "2016-regular.json"? Express will not serve a static file by default, and you are trying to retrieve this static resource withfetch
. See this link – Eric Commented Nov 27, 2017 at 17:48
1 Answer
Reset to default 5I think the bottom line is that you need to make sure your JSON file is reachable/loadable, and then make sure it is valid. Here is a minimal working example. You app.js should be simply:
var express = require('express');
var index = require('./routes/index');
var app = express();
app.set('views', 'views');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/', index);
module.exports = app;
Your routes/index.js is simply:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
And your views/index.ejs should be:
<html>
<body>
<div id="output">JSON contents will appear here.</div>
<button id="getProperty">Click to load JSON</button>
<script>
document.getElementById('getProperty').addEventListener('click', getProperty);
function getProperty() {
fetch("./2016-regular.json")
.then((res) => res.json())
.then((data) => {
document.getElementById('output').innerHTML = JSON.stringify(data);
});
}
</script>
</body>
</html>
Finally, make sure your JSON file is saved at ./public/2016-regular.json. Here is mine:
{ "item1": "value1", "item2": "value2", "item3": "value3" }
TEST 1 Make sure your JSON file is reachable my pointing your browser to http://localhost:3000/2016-regular.json (note you may have to change the port if you are running on a different port).
TEST 2 Navigate to http://localhost:3000/ and click on the button. The file contents should appear in the results div.
Full working code is available here. Just clone the repository, then
cd exp1
npm install
npm start