2017-02-16 83 views
1

時獲取收益400我希望做的JavaScript中的以下內容:張貼到localhost

curl --data "client_id=admin-cli&username=xx&password=xx&grant_type=password" http://localhost:8082/auth/realms/mine/protocol/openid-connect/token 

這裏是我的嘗試:

const data = {"client_id":"admin-cli","username":"xx","password":"xx,"grant_type":"password"}; 
    const formData = new FormData(); 
    for(name in data) { 
     formData.append(name, data[name]); 
    } 
    fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token", { 
     method: "POST", 
     body: formData 
    }) 
     .then(function (response) { 
      return response.text(); 
     }) 
     .then(function (text) { 
      console.log('Request successful', text.length,text); 
     }) 
     .catch(function (error) { 
      console.log('Request failed', error) 
     }); 

它產生錯誤:

POST http://localhost:8082/auth/realms/mine/protocol/openid-connect/token 400 (Bad Request) 
localhost/:1 Fetch API cannot load http://localhost:8082/auth/realms/mine/protocol/openid-connect/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:18080' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 
bundle.js:24428 Request failed TypeError: Failed to fetch 

我在做什麼錯?我正在做一個概念驗證,所以只要它返回令牌,我就會滿意於任何解決方案。

我也曾嘗試:

fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token?client_id=admin-cli&username=sa&password=sa&grant_type=password", { 
      method: "POST" 
     }) 

具有相同的結果。

回答

1

-d/--data選項curl發送請求與Content-Type: application/x-www-form-urlencoded並與格式化就像一個查詢串中的數據,作爲一個單一的字符串與由&分離的參數,並通過前面=的值。

所以效仿的是,你需要做的:

fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token", { 
    method: "POST", 
    headers: { 
     "Content-type": 
     "application/x-www-form-urlencoded; charset=UTF-8" 
    }, 
    body: 
     "client_id=admin-cli&username=xx&password=xx&grant_type=password" 
}) 

FormData格式的數據multipart/form-data,這是不是你想要的,如果你的目標是複製這種curl電話。

1

Body屬性使用json字符串kindy請問您可以試試以下 還要注意Get和Head HTTP請求不能有body。

fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token", { 
    method: "POST", 
    body: JSON.stringify(formData) 
})