Axios posting empty request
Asked Answered
E

8

15

I am trying to send an axios request to the backend, but it ends up having an empty body, and i do not understand why it does that. This is the code for the request:

axios.post('/register', {email: email, password: password, username: username, company: company}).then(response => {
    console.log(response.data);
});  

And this is the code for the backend:

authRouter.post('/register', (request, response) => {
    console.log(request.body);

});

And this one outputs an empty request.body. I've also checked the JSON sent, and it is not empty at all. Is there a way to see what is the form of the request before being sent? This authRouter is a module.export, that is being used by the main app module. This app module has this configuration:

app.use(express.static("public"));
app.use(session({ secret: "shh", resave: false, saveUninitialized: false }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());

app.set('views', __dirname + '/views');
app.set('view engine', 'pug');

app.use(authRouter);

https.createServer({key: fs.readFileSync('ssl/key.pem'), cert: fs.readFileSync('ssl/cert.pem')}, app).listen(8080);
Ernst answered 2/7, 2018 at 21:6 Comment(6)
Are you using body-parser properly?Distance
Do you have JSON parsing middleware?Milkfish
Yes, I edited my question to include app configuration.Ernst
I'm guessing that the body-parser might be the issue, since on another occasion, I was using this module without urlencoded part, and I had no problem.Ernst
Or an axios header problem. I see that I should use Content-Type application/x-www-form-urlencoded, but isn't this axios default?Ernst
This is the issue indeed.Ernst
E
36

The issue came from the fact that body-parser wants an x-www-form-urlencoded request, and I wasn't providing one.

I've set the header for the axios request to it, and the code looks like this:

axios.post('/register', {
  email: email,
  password: password,
  username: username,
  company: company
}, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(response => {
    console.log(response.data);
  });
Ernst answered 2/7, 2018 at 21:32 Comment(0)
Z
7

in my case I declare "Content-Type": "application / json" in the axios headers. For ease, I declare in the global attribute of axios.

in this way

axios.defaults.headers.common = {
  "Content-Type": "application/json"
}

Now its works

Zonked answered 30/10, 2018 at 16:33 Comment(0)
C
5

To resolve my problem, I was been constraint to do essentially this

let config = {
               headers: {
                  'Content-Type': 'application/x-www-form-urlencoded',
               } 
          }

let params = new UrlSearchParam();
    params.append('var1', 'val1');
    params.append('var2', 'val2');

//Finally

axios.post('gotourl', params, config).then( ( response ) => {
      console.log(response.data);
});

More informations

Coridon answered 18/6, 2019 at 0:32 Comment(0)
L
4

You can use qs to serialize your payload.

Install: npm i qs

const qs = require('qs');
axios.post('/post/submit-timesheet', qs.stringify({your: 'data'}))
    .then(res => console.log(res))
    .catch(err => console.log(err));

Hope this helps. :)

Listed answered 10/12, 2019 at 15:57 Comment(0)
G
1

I've stack in same issue just now, and the problem in my case is in transformRequest function: it return data without JSON.stringifying it. That's how transformRequest func shoul looks like (logger in my case, using TypeScript):

const requestLogger = <D>(url: string, methodName: string) => (data: D): string => {
    console.log(`Request ${methodName} ${url}\n Body:,`, data)
    return JSON.stringify(data);
}

and finally my post static method looks like so:

static baseHeaders: Object = {
        "Content-Type": "application/json"
    };

static post<T, B>({
        url,
        body,
        params = {},
        headers = {},
        needThrowError = false,
    }: IPost<B>): Promise<void | AxiosResponse<T>> {
        const rest = axios.create({
            params,
            baseURL: this.baseUrl,
            headers: {...this.baseHeaders, ...headers},
            timeout: TIMEOUT,
            transformRequest: requestLogger<B>(url, 'POST'),
            transformResponse: responseLogger<T>(url, 'POST'),
        })

        return rest.post(
            url,
            body,
        ).catch((error) => {
            defaultNetworkErrorHandler(error);
            if (needThrowError) {
                throw error;
            }
        });
    };
Gorges answered 27/6, 2020 at 2:15 Comment(0)
A
1

Then problem in my case was that my nodeJS server needed to parse the incoming JSON payload with the express.json() middleware. I put this code in my main index.js file:

app.use(express.json());

And it fixed it.

Account answered 16/1, 2023 at 23:50 Comment(0)
H
0
 let data = qs.stringify(
              {
              username:this.username,
              password:this.password
          }
          )
          
          axios.post(`${this.$store.state.backendHost}/register`,data,
          {
              headers:{
                   'Content-Type': 'application/x-www-form-urlencoded'
              }
          })

This is the final version of code that I ended up with. Not using qs.stringify() resulted in output something like that : { '{"username":"shelly","password":"hell"}': '' } which is not desirable. Another thing is You can use "postman" for generating the codeenter image description here

I hope this will help, Im new to stackoverflow. so ignore if there's any mistake

Hemicrania answered 15/3, 2021 at 6:25 Comment(0)
O
0

I use following middleware in my index.js file and it solve my problem

app.use(bodyParser.json());

Oversubtle answered 18/8, 2024 at 10:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.