0

大家好,我下面这个https://marmelab.com/admin-on-rest/index.html,对于登录的事情,我在下面https://marmelab.com/admin-on-rest/Authentication.html无法从管理上休息发送正确的JSON PARAMS(reactJS)

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侧的PARAMS时,无法得到PARAMS体,下面是结果:

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

我试图改变发送标题(内容类型)请求:

... 
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> 

那么如何让越来越PARAMS例如:

的ActionController ::参数{ “用户名”=> “JHON” “password”=>“doe”,“controller”=>“sessions”,“action”=>“create”}允许:false>

回答

2

默认情况下,如果您想发送json格式,必须在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}) 
    }) 
+0

嗨穆罕默德谢谢,但还是不能让PARAMS – Khalid

+0

你面对访问允许起源问题看到允许在轨道上CORS后端我得到了在内容类型T的问题要小,而不是像资本-----头文件:{ “Content-type”:“application/json; charset = UTF-8”, } –

+0

请阅读https://github.com/cyu/rack-cors –

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(); 
     });