简体   繁体   中英

Unable to fetch data from MySQL database with Fetch API

I'm able to post successfully to MySQL database with Fetch API. The problem I'm having is trying to retrieve data from my database.

client.js:


const output = document.getElementById('output');
const username = document.querySelector('#username');
const date = document.querySelector('#date');
const submitbtn = document.querySelector('#submitbtn');
const commentOutput = document.querySelector('#message');
const form = document.querySelector('#form');
const comments = document.getElementById('message')


form.addEventListener('submit', function(e) {
    e.preventDefault(e);
    sendMessage();

    let formMessage = new FormData(form);

    formMessage.append('api-key', 'myApiKey');


    fetch('http://localhost:5502/superhero', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({ comments: comments.value })

    }).then(function(response) {
        console.log(response)
        console.log(JSON.stringify({ comments: comments.value }))
        return response.json()
    }).then(function(data) {
        console.log(data);
    }).catch(function(error) {
        console.log(error);
    });
})



submitbtn.addEventListener('click', function() {
    fetch('http://localhost:5502')
        .then(response => {
            if (response.ok) {
                console.log('success')
            } else {
                console.log('failure')
            }
            return response.json();
        })
        .then(data =>
            console.log(data))
        .catch(error => console.log('Error'))


    var newUser = document.createElement("div");
    var newName = document.createElement("h5");
    var newDate = document.createElement("h5");
    var newMessage = document.createElement("h6");

    newName.textContent = comments.value;
    newDate.textContent = message.value;
    newMessage.textContent = message.value;

    output.appendChild(newName);
    output.appendChild(newDate);
    output.appendChild(newMessage);

    output.appendChild(newUser);
})

The problem here is the fetch method under the submitbtn: Output: 在此处输入图像描述

index.js:

router.post("/superhero", function(req, res) {

    const user = req.user;
    const comments = req.body.comments;

    sqlDatabase.query("INSERT INTO comments (user_id, comments) VALUES (?, ?)", [user, comments],
        function(error, results, fields) {
            console.log(results);
            console.log(comments);
            console.log('This is: ', comments)
            console.log(error)
            if (error) throw error;

        });
})


router.get("/superhero", authenticationMiddleware(), function(req, res, err) {

    sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
        function(error, results, fields) {
            if (error) throw error;
            console.log(results);
            console.log(error);
            res.render('superhero');

        })
})

I want to retrieve that data under router.get

Hope this is enough details. Thanks in advance. Noob by the way.

The res.send actually send back the JSON response

    router.get("/superhero", authenticationMiddleware(), function(req, res, err) {

    sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
        function(error, results, fields) {
            if (error) throw error;
            console.log(results);
            console.log(error);
            res.send({heros: results}); //<-- send back the JSON response

        })
})

Also, you can add condition if you're rendering on the server side as well

if (req.accepts('json')) {
  res.send({hero: 'superhero'}); // <-- try sending back JSON object but rather a string
 // OR
 res.send({heros: results});
else {
 res.render('superhero');
}

If you're using Express then you can use response.json method as well.

Finally got the results I wanted. I just created another api for retrieving data from my server file and changed this:

 fetch('http://localhost:5502/superhero')

to:

  fetch('http://localhost:5502' + '/get_messages')
app.get("/get_messages", function(request, result) {
    sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
        function(error, results) {
            result.end(JSON.stringify(results));
            console.log(results);
        });
});

So I have a route for rendering a view, and one for retrieving the data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM