[英]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.