Issue
I’m not sure where I’m going wrong here. I’m trying to pull data from a mysql database and display it on a react page.
Here’s the query:
static getTopPost(){
return new Promise((resolve, reject) => {
pool.query(
'SELECT * FROM blog_post ORDER BY create_date LIMIT 1',
function (error, results, fields) {
if(error) return reject(error);
resolve(results);
}
)
})
}
Here’s the get
router.get('/top', (req, res) => {
const post = req.app.locals.engine.generation.topPost();
PostTable.getTopPost(post)
.then(post => console.log(post))
.catch(error => console.error('error', error));
res.end();
})
Here’s the react:
fetchPost = () => {
fetch('http://localhost:3000/post/top')
.then(response => response.json())
.then(json => {
this.setState({ post: json.post})
})
.catch(error => console.error('error', error));
}
In terminal I see the data(referenced in screenshot):
Screen grab from terminal in IDE
However it doesn’t appear when I load the page. When I check the console in Firefox I get the following message:
error SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Let me know if more info is needed.
Solution
res.end()
means you are returning empty 200 status response. try to res.json()
for json response and pass your post details inside parenthesis.