簡體   English   中英

服務器端代碼無法識別我的req.body.variable,表明它未定義

[英]Server side code does not recognize my req.body.variable, stating that it is undefined

我創建了一個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);
        });
    }
};

主體應采用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",
    }
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM