2017-02-16 82 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) 
})