大家好我跟着这个https://marmelab.com/admin-on-rest/index.html,对于登录的事情,我跟随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();
}
对于使用Rails 5.0的API,当运行上面的代码并在API端调试params时,我无法获得params body,结果如下:
<ActionController::Parameters {"controller"=>"sessions", "action"=>"create"} permitted: false>
我尝试将已发送的标头(Content-Type)请求更改为:
...
headers: new Headers({"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"}),
...
在API端再次调试params,结果:
<ActionController::Parameters {"{\"username\":\"jhon\",\"password\":\"dow\"}"=>nil, "controller"=>"sessions", "action"=>"create"} permitted: false>
那么如何让params这样:
ActionController ::参数{&#34;用户名&#34; =&gt;&#34; jhon&#34;,&#34;密码&#34; =&gt;&#34; doe&#34;,&# 34;控制器&#34; =&gt;&#34;会话&#34;,&#34;操作&#34; =&gt;&#34;创建&#34;}允许:false&gt;
答案 0 :(得分:2)
默认情况下,浏览器需要表单数据,如果你想发送json格式,那么ypu必须在API提取方法中设置json属性为true,见下文 -
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})
})
答案 1 :(得分:1)
如果您希望json解释您的角色,您应该添加charset=utf-8
来解析。
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'
}),
})
确保正确保存令牌。对于我,我没有使用token
作为admin-on-rest建议,我使用了名为access-token
的响应标头,因此我直接在响应中保存在localStorage上。这可能会影响代码的结果。
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();
});