发布到localhost时,fetch返回400

时间:2017-02-16 08:56:01

标签: javascript fetch-api

我希望在javascript中执行以下操作:

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"
        })

具有相同的结果。

2 个答案:

答案 0 :(得分:1)

curl的{​​{3}}选项发送请求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"
})

-d/--data将其数据格式化为multipart/form-data,如果您的目标是复制curl来电,那么这不是您想要的。

答案 1 :(得分:1)

Body属性请使用json字符串,请您尝试以下 另请注意,Get和Head HTTP请求不能包含主体。

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