0

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.

1 Answer 1

1

res.end() means you are returning empty 200 status response. try to res.json() for json response and pass your post details inside parenthesis.

Sign up to request clarification or add additional context in comments.

1 Comment

After re-reading, those last 6 words mattered the most. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.