Home > Back-end >  Nodejs Axios Post returns undefined value
Nodejs Axios Post returns undefined value

Time:01-01

I am using React NodeJS & Axios but have been trying to send a post request but experiencing difficulties.

The request seems to be posting successfully, but all actions at the nodejs server is returning in the "undefined" data value, even if the data is passed successfully shown in the console.

REACT

const fireAction = (data1, data2) => {
    const data = JSON.stringify({data1, data2})
    const url = `http://localhost:5000/data/corr/fire`;
    const config = {
        headers: {
           'Content-Type': 'application/x-www-form-urlencoded',
           'Authorization': 'AUTHCODE',
        }
    }
        axios.post(url, data, config)
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
}

fireAction("Oklahoma", "Small apartment")

NODE

app.post('/data/corr/fire', async (req, res) => {
    try {
      const data = req.body.data1;
      console.log(data)
    } catch(e) {
      res.send({success: "none", error: e.message})
    }
  });

Result of node: "undefined"

I have added the following body parser:

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

I am not sure why this error is happening. I see there is similar questions to mine: however none of them are applicable as I'm using both express and body parser which is already suggested.

CodePudding user response:

You're POSTing JSON with a content-type meant for forms. There's no need to manually set content-type if you're sending JSON, but if you want to manually override it, you can use 'Content-Type': 'application/json', and access the response in your route with req.body. If it does need to be formencoded, you'll need to build the form:

const params = new URLSearchParams();
params.append('data1', data1);
params.append('data2', data2);
axios.post(url, params, config);
  • Related