2

I send http post from my react app to API like this :

const request = new Request('http://localhost:9000/login', {
  method: 'POST',
  headers: new Headers({"Accept": "application/json", 
              "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}),
  body: JSON.stringify({ username: username,
               password: password})
})
return fetch(request)
  .then(response => {
    if (response.status < 200 || response.status >= 300) {
      throw new Error(response.statusText);
    }
    return response.json();
  })
  .then(({ token }) => {
    localStorage.setItem('token', token)
  });

And I debug it in console on my rails app, and this is the output :

<ActionController::Parameters {"{\"username\":\"qqqqqq\",\"password\":\"ssssss\"}"=>nil, "controller"=>"sessions", "action"=>"create"} permitted: false>

How do I parsing the params above, I need get username & password params ?

3 Answers 3

4

You could do something like this with native Ruby JSON library:

@json = JSON.parse(request.body.read)
username = @json['username']
password = @json['password']

You take the POST request data and then parse to JSON.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks charliesttrada
1

I might be late to answer, but maybe I can help anyone, who stumbles upon this thread.

In your React application you set the Content-Type header to type application/x-www-form-urlencoded, but your body is in JSON format. Hence, your Rails app does not parse the parameters correctly due to the wrong content type.

The solution would be to set Content-Type to application/json;charset=UTF-8

Comments

0

rails provides a JSON class that codes and decodes json for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.