0

I have a RoR api and I'm building a react with redux page. I'm calling my user's todos. This is how it works so far: When it sign up, i store the token key in the state, and then use that to make an api call to get my todos (index). I have my action here:

  def index
    @todos = current_user.todos
    json_response(@todos)
  end

This is the block that is failing:

 loginHandler() {
        const { email, password } = this.state;
        const { login, tokenize, token } = this.props;
        axios.post('http://localhost:3001/auth/login', {withCredentials: true,
        email: email, password: password})
            .then(response => {
                login(true);
                tokenize(response.data.auth_token);
                axios.get('http://localhost:3001/todos', {Authorization: token}) // Error occurs
              .then(response => {
                console.log(response);
              }).catch(error => console.log(error));
            }).catch(error => console.log(error));
    }

Where tokenize and login are actions passed to redux. The error is in the second axios call, where I'm getting a 422 Unprocessable Entity. I made a manual test with httpie from my terminal and there, it works. Also debug my todos#index action and this is the error from the server-side:

AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".).

My RoR is 5.2 and ruby 2.6.3. The login works, the signup works, but the get method for todos is not working ONLY in react. In httpie from my terminal it does work. I've been fighting for a while with this one and no resource online has been really helpful, which made me think there's some typo there, that I haven't seen.

1 Answer 1

2

Authorization should be sent in headers:

axios.get('http://localhost:3001/todos', { headers : { Authorization: token } })

https://flaviocopes.com/axios-send-authorization-header/

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

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.