Reputation: 672
In a Rails API, I have a login
POST method in my UsersController
which takes 2 parameters (mail and password) and check in DB if a record is found and if so returns it.
def login(mail, password)
user = User.where(mail: mail, password: password)
render json: user
end
In my front side, in React, I call this method with fetch
which takes the mail and password values in a form:
login = () => {
if(this.state.mail != null && this.state.password != null){
fetch('http://127.0.0.1:3001/api/login', {
method: 'post',
credentials: 'include',
body: JSON.stringify({
mail: this.state.mail,
password: this.state.password
}),
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
})
.then((res) => {
console.log(res)
if(res.data.length === 1 ){
const cookies = new Cookies();
cookies.set('mercato-cookie',res.data[0].id,{path: '/'});
this.setState({redirect: true})
}
})
}
}
The method is well called, but I have the following error : ArgumentError (wrong number of arguments (given 0, expected 2))
, I tried it with Postman with the same result so I guess the problem is a Rails one.
Here is my cors configuration :
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:3000'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
credentials: :true
end
end
I thought the credentials: :true
would resolve the problem but it does not.
I'm out of ideas here :/
Upvotes: 0
Views: 175
Reputation: 30056
Rails' actions do not handle parameters in that way. You have to use params
.
def login(mail, password)
user = User.where(mail: mail, password: password)
render json: user
end
to
def login
mail, password = params.values_at(:mail, :password)
user = User.where(mail: mail, password: password)
render json: user
end
Upvotes: 1