Reputation: 895
Hi all I'm following this https://marmelab.com/admin-on-rest/index.html, for login thing, I'm following https://marmelab.com/admin-on-rest/Authentication.html :
import { AUTH_LOGIN } from 'admin-on-rest';
import restClient from './restClient';
export default (type, params) => {
if (type === AUTH_LOGIN) {
const { username, password } = params;
const request = new Request('http://localhost:9000/login', {
method: 'POST',
headers: new Headers({"Content-Type": "application/json"}),
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)
});
}
return Promise.resolve();
}
For API I'm using Rails 5.0, when running the code above and debug the params on API side I can't get params body, here is the result :
<ActionController::Parameters {"controller"=>"sessions", "action"=>"create"} permitted: false>
I tried to change sent headers (Content-Type) request to :
...
headers: new Headers({"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"}),
...
And debug the params again on API side, and the result :
<ActionController::Parameters {"{\"username\":\"jhon\",\"password\":\"dow\"}"=>nil, "controller"=>"sessions", "action"=>"create"} permitted: false>
So how to make getting params such :
ActionController::Parameters {"username"=>"jhon", "password"=>"doe", "controller"=>"sessions", "action"=>"create"} permitted: false>
Upvotes: 0
Views: 178
Reputation: 23
If you wish the json to interprete your characters, you should add the charset=utf-8
to parse.
const request = new Request('http://localhost:9000/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json'
}),
})
And be sure you are saving the token correctly. For me I didn't use the token
as the admin-on-rest suggested, I used a response Header named access-token
, so I saved on localStorage directly in the response. Maybe that will influence the result on your code.
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
localStorage.setItem('access-token', response.headers.get('access-token'));
return response.json();
});
Upvotes: 1
Reputation: 251
By default browser takes form data if you want send json like format then ypu have to set json property true in API fetch method see below--
const request = new Request('http://localhost:9000/login', {
method: 'POST',
json: true,
headers: new Headers({"Content-type": "application/json"}),
body: JSON.stringify({ username: username,
password: password})
})
Upvotes: 2