我正在创建一个Web应用程序,该应用程序应在每次按下特定按钮时将信息从客户端发送到服务器端。当我按下按钮时,终端会继续告诉我,我尝试通过邮寄请求正文传递的值是不确定的。
客户端代码(从何处调用按钮)-
function upvote(elem) {
var parentID = elem.parentNode.id;
console.log('Upvote button was clicked' + parentID);
fetch('/upvote', { //This is called to pass the body data to server side code
method: 'post',
body: JSON.stringify({
id: parentID
})
})
.then(function(res) {
if(res.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
function downvote(elem){
var parentID = elem.parentNode.id;
console.log('Downvote button was clicked');
fetch('/downvote', { //This is called to pass the body data to server side code
method: 'POST',
body: JSON.stringify({
id: parentID })
})
.then(function(res) {
if(res.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
setInterval(function() {
fetch('/ranking', {method: 'GET'})
.then(function(response) {
if(response.ok) return response.json();
throw new Error('Request failed.');
})
.then(function(data) {
})
.catch(function(error) {
console.log(error);
});
}, 1000);
我的app.js(服务器端代码)-
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const {getLoginPage, login} = require('./routes/index');
const {players, questionsPage, upvoteQues, downvoteQues, ranking, addQuestionsPage, addQuestion, deleteQuestion, editQuestion, editQuestionPage} = require('./routes/question'); //All my routes
const port = 5000;
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: ''
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); port
app.set('views', __dirname + '/views'); folder to render our view
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.get('/', getLoginPage);
app.get('/questions', questionsPage);
app.get('/add', addQuestionPage);
app.get('/edit/:id', editQuestionPage);
app.get('/delete/:id', deleteQuestion);
app.get('/ranking', ranking);
app.post('/', login);
app.post('/add', addQuestion);
app.post('/edit/:id', editQuestion);
app.post('/upvote', upvoteQues); //This is then used
app.post('/downvote', downvoteQues); //This is then used
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
我的question.js(更多服务器端代码,只是分成一个不同的文件)
const fs = require('fs');
module.exports = {
questionsPage:(req, res) =>{
let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC";
db.query(query, (err, result) => {
if (err) {
console.log('Query error');
res.redirect('/');
}
res.render('questions.ejs', {
title: "JustAsk!",
questions: result,
});
});
},
upvoteQues: (req, res) => {
console.log(req.body.id); //Error here
let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'" //Error here
db.query(updateQuery, (err, result) => {
if(err){
console.log('Query error');
res.redirect('/players')
}
});
},
downvoteQues: (req, res) =>{
console.log(req.body.id); //Error here
let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'" //Error here
db.query(updateQuery, (err, result) => {
if(err){
console.log('Query error');
res.redirect('/players')
}
});
},
ranking: (req, res) => {
let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC";
db.query(query, (err, result) => {
if (err) {
console.log('Query error');
}
res.send(result);
});
}
};
答案 0 :(得分:0)
正文应为JSON格式,而不是字符串。
body: JSON.stringify({
id: parentID
})
更改为:
body: { id: parentID }
and content type should be 'application/json` like below.
fetch('/url', {
method: 'POST',
body: {id: parentID },
headers: {
"Content-Type": "application/json",
}
})