3

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');
 });
Amantuer
  • 53
  • 5
  • Hi Amantuer, Some question to understand your problem better, Are you sure you want to do a GET method and not a POST ? – Sayf-Eddine Feb 22 '21 at 07:46
  • @Sayf-Eddine I want to serach and get values from server according to the user info, so is it right to use get method to pass user info and get values back? – Amantuer Feb 22 '21 at 07:52
  • 1
    If you only search the values from server according to the user info why you don't use the express middleware `/:userid` you will access to the parameter using `req.params.userid` ? Because according to what your looking for i think it's the best way to do it. According to the http standards for sending the data we generally use POST request. – Sayf-Eddine Feb 22 '21 at 07:59

1 Answers1

1

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

Sayf-Eddine
  • 559
  • 6
  • 15