0

I am trying to access the expression passed from the backend to the frontend through axios.

Producer side:

const axios = require('axios');
const URL = "http://localhost:5000/"
let n1 = 3
let n2 = 5
let sum = n1+n2;



axios.post(URL, JSON.stringify({
    expression: sum,
  }))
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

and on the consumer side:

const express = require('express')
const app = express()

app.post('/', (req, res) => {
  console.log(req.body);
})

app.listen(5000, () => console.log())

Ultimately, I would like to have the consumer side log "8"

  • 1
    And what are you actually seeing? – punund Jun 30 '22 at 18:27
  • At the moment, I have console.log(req) which gives me a large object. I would like to console.log(req.body) to return the value of the defined variable 'sum' – oobthenewb Jun 30 '22 at 18:32
  • Maybe this is the answer you need https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application – Yarin Levi Jun 30 '22 at 18:43
  • On the client-side, I don't think the `JSON.stringify` method is necessary. Try to remove it. Document here: https://axios-http.com/docs/post_example – Đăng Khoa Đinh Jul 01 '22 at 07:29

3 Answers3

1

You don't need to convert to JSON, axios serves JSON natively.

Add to the server:

app.use(express.json())

Just send you data:

axios.post(URL, { expression: sum, })
  .then(console.log)
  .catch(console.err)
punund
  • 4,321
  • 3
  • 34
  • 45
0

From the "express" documentation:

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

Try including this before you try to register the endpoint:

const bodyParser = require('body-parser')

app.use(bodyParser.json())

You can also use express.json() and drop the 'body-parser' dependency:

// const bodyParser = require('body-parser')

app.use(express.json())
Jared A Sutton
  • 369
  • 3
  • 8
  • Hey, I have tried this method, and I am getting ```{}``` this is a good start. I would like to return ```13``` – oobthenewb Jun 30 '22 at 19:14
0

Axios have some security measures as well, you should put your IP address in const URL = "http://localhost:5000/"