2017-02-21 59 views
0

我從發送HTTP POST JSON字符串參數我的反應,應用API是這樣的:如何解析在軌

const request = new Request('http://localhost:9000/login', { 
    method: 'POST', 
    headers: new Headers({"Accept": "application/json", 
       "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}), 
    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) 
    }); 

我調試它在我的Rails應用程序控制臺,這是輸出:

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

如何解析上面的參數,我需要獲取用戶名&密碼參數?

回答

0

你可以做這樣的事情與原生Ruby JSON庫:

@json = JSON.parse(request.body.read) 
username = @json['username'] 
password = @json['password'] 

你拿POST請求的數據,然後分析,以JSON。

+0

感謝charliesttrada – Khalid