M. Rodella
M. Rodella

Reputation: 3

NodeJS (back-end) receive data from POST call then how to show in ReactJS (front-end)?

I'm new to NodeJS/ReactJS. I've got a NodeJS backend that receive a JSON POST from an external resource. I'm able to show data in console in express-async-router request.

This is my NodeJS back-end

const AsyncRouter = require("express-async-router").AsyncRouter;
const router = AsyncRouter();
const jsonParser = require("body-parser").json({limit: "500kb"});
const validate = require("express-validation");
const schema = require("./schema");

router.use(jsonParser);

router.post("/exist", async (req, res) => {
  // console.log("Request");
  // console.log(req);
  return res.status(200).json({
    body: req.body,
    msg: "Ciao"
  });
});

module.exports = router;

This code print in console the POST request body.

I would show this data in ReactJS frontend but I've got no idea how to do it.

What is the best practice to achieve my goal?

Thanks

Upvotes: 0

Views: 3137

Answers (2)

Sandeep Patel
Sandeep Patel

Reputation: 5148

You can use Fetch, Axios or superagent module to make api call. please refer this for more details https://reactjs.org/community/data-fetching.html

https://daveceddia.com/ajax-requests-in-react/

below is a sample react component to make HTTP call on button click event

import axios from 'axios'

class App extends Component {
  constructor () {
    super()
    this.state = {
      username: ''
    }

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick () {
    axios.get('https://api.github.com/users/sandeepp2016')
      .then(response => this.setState({username: response.data.name}))
  }

  render () {
    return (
      <div className='button__container'>
        <button className='button' onClick={this.handleClick}>Click Me</button>
        <p>{this.state.username}</p>
      </div>
    )
  }
}
export default App

Upvotes: 2

davidfloyd91
davidfloyd91

Reputation: 517

You'll need your React frontend to query the Node backend. The simplest way to do this is using the Fetch API, which is well-documented here.

You'll also need to set up a route in your Node backend to accept the fetch request from the frontend and return the desired resources. The express-async-router docs are probably the best place to start.

Upvotes: 0

Related Questions