Communication between react and api

98 Views Asked by At

Everything ok? I created a react application that communicates with a rails api. It is a very simple application, but there is this communication between react and api.

My question is… Do I need to create a token of authentication so that third parties do not use my api? Or can I somehow tell my api that it only responds to requests that come from my site?

Thank you for your help!

2

There are 2 best solutions below

0
Diogo Amaral On BEST ANSWER

thank you both that give me some answers.

I came from work now, and sit to study a little, and I found about CORS. That is exactly what I was looking for.

Here is a guide specific about a gem that make it in Rails. https://www.stackhawk.com/blog/rails-cors-guide/

----- edit

As requested... here is my solution.

  1. I installed the gem "rack-cors".

  2. In config/initializers I created the file cors.rb with the following code:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "localhost:3000" #1
    resource "*", #2
      headers: :any,
      methods: [:get] #3
  end
end

#1 -> origins: are the origins that u want to accept connect to the api, in dev environment for example, u should place "localhost:3000" or "127.0.0.1:3000". Very important here!! domain + port, or u will get error.

#2 -> resources: are the resources that the specified domain may access. In example is * for all resources, but u could set just "/orders" or "/users". and even explain for each resource which header or methods u will accept.

#3 -> method: are the http methods that will accept, as: get, post, put etc

2
Ganeshguru On
  1. Okay let me help you with that. I hope you could create a sever with a URL like this: 'localhost:3000/api/' or 'https://something.api/api'. You can use this API in React by using Axios methods like: axios.get("localhost:3000/api/").

  2. It seems like you want to create a authentication token when someone calling your API. Hence there are several hash libraries are available for creating API tokens according to time, username, etc. You can create it save it to your database. Whenever API call like this 'https://something.api/api/key=hfudjuh8989' you can get the key as from params and use it to verify with your database.