(Why is ‘Hello’ always cut away from the text rendition? Anyways… Hello!)
I’m struggling to find the cause of a
'Failed to execute 'json' on 'Response': Unexpected end of JSON input'
error I’m getting with .json() in the React code below, whether the array in the model is parsed or stringified. The response I get from the console.log(fetchList);
is:
Response {
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3000/"
[[Prototype]]: Response
}
I threw in a console.log inside the controller’s getAllTopics()
function and nothing gets printed, which suggests the request never even reaches the controller?
(Also the async is here only because eventually this is going to connect to a real database and not a mock like now.)
I have a test tomorrow and I can’t move on without having this problem solved! Any idea? 🙂 Thank you!
function TopicContainer () {
const [topicList, setTopicList] = useState([])
const serverURL = 'http://localhost:3000';
async function fetchData () {
const fetchList = await fetch(serverURL);
console.log(fetchList);
const fetchListParsed = await fetchList.json()
setTopicList(fetchListParsed);
}
useEffect(() => {fetchData();}, [])
return (
<div className='topic-container'>
{topicList.map( topic => <Topic key={topic._id} title={topic.title} pubAt={topic.published_at} score={topic.score}></Topic>)}
</div>
)
}
Here’s my express index…
'use strict';
const express = require('express');
const app = express();
const router = require('./router');
const cors = require('cors');
const port = 3000;
app.use(cors());
// app.use(express.json());
app.use(router);
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
…router…
'use strict';
const express = require('express');
const router = express.Router();
const control = require('./control')
router.get('/', control.getAllTopics);
module.exports = router;
…controller…
'use strict';
const model = require('./model');
exports.getAllTopics = async (req, res) => {
try {
const topicList = model;
res.status(200);
res.json(topicList);
}
catch (err) {
console.log('Error retrieving from the database');
res.status(500);
res.json(err);
}
};
…and model.
'use strict';
const db = [
{
_id: "sdk92k20elked202doe2",
title: "Porting from Angular.js to Angular 2",
published_at: "2017-01-08T21:00:11.620Z",
score: 5
},
{
_id: "sdk92k20elked202doe3",
title: "'Being on the edge' by John Middleware.",
published_at: "2017-01-20T09:00:11.620Z",
score: 5
},
{
_id: "sdk92k20elked202doe4",
title: "Porting from Angular.js to Angular 2",
published_at: "2017-01-08T21:00:11.620Z",
score: 5
}
];
module.exports = db;
3