Tuesday 6 June 2017

With a `new Request` in node/react, how to pass params with a GET request?

I have the following API call in my reactjs app:

  static getAllSkills(title_id) {
    const request = new Request(`http://localhost:4300/api/v1/job_title_skills`, {
      method: 'GET',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({title_id: title_id})
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

Which points to a Rails endpoint which expects the param title_id like so:

  def index
    @skills = Skill.where(id: params[:title_id])
    ....
  end

The controller is expecting a GET request however with the above, I'm getting the following JS console error:

Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.

What is the right way to construct the Request and pass the param to the API? Thanks



via AnApprentice

No comments:

Post a Comment