Riley Bracken
Riley Bracken

Reputation: 6399

React Node API Request Design Pattern

I need to make an API request to an external API using an API Key. I know how to make this API request in React by writing a onSubmit function. But since I have an API key that I want to keep a secret I am going to write a simple Node app to house env variables.

Besides messing around in node this is my first production experience with Node and I am wondering if my thought process is correct and if not, the better way to do this.

Most of this question will be pseudo code since I haven't started with the Node portion yet.

The idea is that from within the React component it would call the Node app who in turn would call the external API.

React -> Node -> External API

So the React component would be something like so:

handleSubmit: function() {
  var data = this.refs.testData.getDomNode().value;

  $.ajax({
    url: '/my-node-endpoint',
    dataType: 'json',
    type: 'POST',
    data: { test: data },
    success: function(data) {
      // Whatever success call I want to make
    }.bind(this)
  })
}

And then in my Node app it would like something like this:

app.post('/my-node-endpoint', function(req, res) {
    // Store the values we are posting as JSON
    // Start the post request
    // On End tell the React component everything is ok
    // Prosper
});

As always, thanks for any help that is offered.

Upvotes: 3

Views: 921

Answers (1)

Grace Huang
Grace Huang

Reputation: 5709

Your thought process looks right to me.

If the API you are calling is from a different domain, you will have to build a wrapper on your node server like you did here. Unless the external API supports cross-origin requests with no domain restrictions (such as MapBox web services), you will have to do this.

Several improvements to your code:

  1. As far as I know, you can use React.findDOMNode(this.refs.testData).value instead of this.refs.testData.getDomNode().value. getDomNode() is deprecated in v0.13.
  2. For all the AJAX calls, you can use the Store concept in Flux. The store keeps the states of the data, including updating data through AJAX request. In your React UI code, you just need to call the methods of the store, which makes your UI code clean. I usually create a store class myself without using Flux.

Upvotes: 1

Related Questions