【问题标题】:Unable to fetch data from MySQL database with Fetch API无法使用 Fetch API 从 MySQL 数据库中获取数据
【发布时间】:2020-11-16 09:21:27
【问题描述】:

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

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

这里的问题是submitbtn下的fetch方法: 输出:

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 下检索该数据

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

【问题讨论】:

  • 您是否尝试过记录实际错误?
  • 尝试fetch('http://localhost:5502/superhero'),因为这是您配置的路线,但仅供参考,res.render('superhero') 可能不会以 JSON 响应,因此response.json() 可能会失败
  • res.json(results) 怎么样

标签: javascript mysql node.js fetch-api


【解决方案1】:

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 方法。

【讨论】:

  • res.json() 更合适,尽管 OP 实际上不太想用文字字符串 "superhero" 进行响应
  • @Phil "superhero" 字符串应该被转换为对象。查看我的更新答案
  • 为什么不使用results
  • @Phil 无论他返回什么都取决于他,但它应该是一个对象
  • 好的,我试过你的答案,它会用字符串响应。我将如何渲染路线并一起发送 json。我将处理 json 以在客户端显示。我会同时勾选你的答案,因为它有帮助。
【解决方案2】:

终于得到了我想要的结果。我刚刚创建了另一个 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);
        });
});

所以我有一个渲染视图的路由和一个检索数据的路由

【讨论】:

  • 我相信我会回答您的解决方案,只是您没有在问题中添加Server 侧面渲染。由于您对fetch 有疑问,我回答了这个问题,但是,我还添加了有关如何实现不同渲染的详细信息。
  • 我听到了,但是谢谢,你确实帮助了我。最初,我认为我的问题只是在客户端,直到您指出我没有发回 JSON 对象。
  • StackOverflow,我们(助手)会花时间回答您的问题,如果有人会发布他自己的答案并稍作改动,那肯定不是一个好主意。此外,也应该通过单击数字中间的 (0) 来接受您之前问题的答案
猜你喜欢
  • 2018-07-20
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 2017-02-18
  • 2023-04-05
相关资源
最近更新 更多