gpt4 book ai didi

javascript - 无法从 admin-on-rest (reactJS) 发送正确的 JSON 参数

转载 作者:行者123 更新时间:2023-11-28 18:07:10 24 4
gpt4 key购买 nike

大家好,我正在关注这个 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();
}

对于 API,我使用的是 Rails 5.0,当运行上面的代码并在 API 端调试参数时,我无法获取参数主体,结果如下:

<ActionController::Parameters {"controller"=>"sessions", "action"=>"create"} permitted: false>

我尝试将发送的 header (内容类型)请求更改为:

...
headers: new Headers({"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"}),
...

并在 API 端再次调试参数,结果:

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

那么如何获取这样的参数:

ActionController::Parameters {"username"=>"jhon", "password"=>"doe", "controller"=>"sessions", "action"=>"create"} 允许: false>

最佳答案

默认情况下,如果您想发送类似 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})
})

关于javascript - 无法从 admin-on-rest (reactJS) 发送正确的 JSON 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42361748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com