繁体   English   中英

无法使用 Fetch API 从 MySQL 数据库中获取数据

[英]Unable to fetch data from MySQL database with Fetch API

我可以使用 Fetch API 成功发布到 MySQL 数据库。 我遇到的问题是试图从我的数据库中检索数据。

客户端.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);
})

这里的问题是submitbtn下的fetch方法: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');

        })
})

我想在 router.get 下检索该数据

希望这是足够的细节。 提前致谢。 顺便说一下菜鸟。

res.send实际上发回了JSON响应

    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

        })
})

此外,如果您也在服务器端渲染,您可以添加条件

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');
}

如果您使用的是Express ,那么您也可以使用response.json方法。

终于得到了我想要的结果。 我刚刚创建了另一个 api 用于从我的服务器文件中检索数据并更改了这个:

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

至:

  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);
        });
});

所以我有一条用于渲染视图的路线,还有一条用于检索数据的路线

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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