Search code examples
javascriptmysqlnode.jsexpressvuex

express.js get method cannot get req.body value


I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".

router.get('/',async function(req,res){
    const userId = req.body.userid;
    console.log("req body is: "+req.body);
    console.log("req.body.userid is: "+req.body.userid);
    .....
}

In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";

      async getsp(){         
        var userinfo = JSON.parse(localStorage.getItem('user'));
        console.log("post userid: "+userinfo.userid);
        var userid = userinfo.userid;
        var obj = {userid}; 
        return await axios.get('//localhost:8081/getSp',obj)
        .then(...)
      },

And in the main router file I used body-parser, the file context is below:

require("dotenv").config();

const express = require('express');      
const bodyParser = require('body-parser');
var cors = require('cors');

const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');

const app = express();        
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors()) 
app.use(express.json());

app.use(
   express.urlencoded({
   extended: true
   })
 );
 app.use("/signup",signup);
 app.use("/dologin",login);
 app.use("/createEvsp",createEvsp);
 app.use("/getSp",getSp);
 //app.use("/createFile",createFile);

 app.listen(8081,function () {    
     console.log('Server running at 8081 port');
 });

Solution

  • The problem was an HTTP method understanding and how express works

    To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid

    According to the http standards for sending the data we generally use POST request. There is a good answer in stack here Information about Get HTTP Request

    Sayf-Eddine