【问题标题】:fetch returns 400 when posting to localhostfetch 在发布到 localhost 时返回 400
【发布时间】:2017-02-16 19:18:18
【问题描述】:

我希望在 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"
        })

结果相同。

【问题讨论】:

    标签: javascript fetch-api


    【解决方案1】:

    curl-d/--data 选项使用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 调用,这不是您想要的。

    【讨论】:

      【解决方案2】:

      body属性使用json字符串,请尝试以下 另请注意,Get 和 Head HTTP 请求不能有正文。

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

      【讨论】:

        猜你喜欢
        • 2020-11-15
        • 1970-01-01
        • 2022-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多