0

Im trying to send a connect call to my api from my vue (i use vue.js), but when i get the object req.body in my back, the object is empty

I've read this : Axios post request.body is empty object but it didn't help me

(it works from Postman with the body filled and the option x-www-form-encoded)

i got this got from my Vue : My vue service.js

import Axios from 'axios';

class APIClient {
    constructor () {
        this.client = Axios.create({
            baseURL: 'http://localhost:8080'
        });
    }

    async connect () {

        const params = new URLSearchParams();
        params.append('mail', 'test');
        params.append('pwd', 'mypwd');
        return await this.client.get('/api/user/auth', params);

    }

and i got this in my back : index.ts :


import express from "express";
var cors = require('cors');
import "reflect-metadata";
var bodyParser = require('body-parser')

const http = require('http');
const MainRouter = require('./routes/main_router');

let port = 8080;
const server = express();

server.use(cors({origin: true}))
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}))

let mainRouter = new MainRouter(server);

const httpServer = http.createServer(server);
httpServer.listen(port);
console.log('Server is listening');

and the main_router.ts


import express from 'express';
import mysql from "promise-mysql";

export default class MainRouter {

    public server: express.Express;
    
    constructor (server: express.Express) {
        super();
        this.server = server; 
        this.server.get("/api/user/auth", async (req: any, res: any) => {
            if (req.body) //the req.body is equal to {} instead of {mail: 'test', ...
                return res.json(await this.userManager.getUserByCredidentials(req.body));
            else return res.json([])
        });    
    }
}

module.exports = MainRouter;

I don't know if i have something to add in my express server or in my vue with axios ?

Jesus
  • 35
  • 6

1 Answers1

1
  1. You are passing the mail and pwd as GET parameters and not at the request body. You can access the using req.query, but ....
  2. You should avoid sending creds as parameters of the url with GET, use the body and POST instead. For more information see this post.

Here is an example:

return await this.client.post('/api/user/auth', {
   mail: "test",
   pwd: "mypwd"
});

and of course do not forget to change this.server.get("/api/user/auth",... to this.server.post("/api/user/auth",...

tjarbo
  • 711
  • 4
  • 13