'how to perform operations with json string from axios?

Background

I am passing variable from my frontend HTML file using axios

var idToken1 = result.getIdToken();
                    
axios({
  method: 'post',
  url: '/trial',
  data: idToken1,
  headers: {'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (response) {
    //handle success
    console.log(response);
})
.catch(function (response) {
    //handle error
    console.log(response);
});

in my app.js under route getting this as output,here all the values are present in key and key values is empty. so i think i need a way to parse those keys first

 {
      '{"payload":{"cognito:username":"jatin","exp":1620965984,"iat":1620962384,"email":"[email protected]"}}': ''
    }

i want to extract "email":"[email protected]"

update: in app.js i am already using express native parser app.use(express.json()); app.use(express.urlencoded({ extended: true }));`



Solution 1:[1]

The problem was with axios. axios needed object to be send as json object. var idToken1 = result.getIdToken();

the following code results in proper JSON object in my backend

axios({
  method: 'post',
  url: '/trial',
  data: { idToken: idToken1 },
  headers: { 'Content-Type': 'application/json' }
})
.then(function (response) {
  //handle success
  console.log(response);
})
.catch(function (response) {
  //handle error
  console.log(response);
});

Solution 2:[2]

A parser is required if you want to get the http body as object:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

Then you can use req.body to get the http body sent by your html web:

app.post('/trial', function(req, res) {
  var email = req.body.payload.email;
  //etc
});

Solution 3:[3]

The Problem cause is 'Content-Type' is should be 'application/json'

axios({
        method: 'post',
        url: '/trial',
        data: idToken1,
        headers: { 'Content-Type': 'application/json' }
    })
        .then(function (response) {
            //handle success
            console.log(response);
        })
        .catch(function (response) {
            //handle error
            console.log(response);
        });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jatin Mehrotra
Solution 2
Solution 3 Ahmad Shbita