javascript - 发布到 localhost 时 fetch 返回 400

标签 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

我做错了什么?我正在进行概念验证,因此只要它返回给我 token ,我都会对任何解决方案感到满意。

我也尝试过:

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

结果相同。

最佳答案

-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 调用,这不是您想要的。

关于javascript - 发布到 localhost 时 fetch 返回 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269087/

相关文章:

javascript - 导出默认异步函数未在当前文件中定义

javascript - react 原生 TypeError : Network request failed with fetch()

javascript - jQuery 事件气泡

javascript - Ember - Controller 的内容和模型属性有什么区别

javascript - Reactjs:文档未定义

javascript - React 无法读取未定义的属性映射

unit-testing - React Native-在单元测试中模拟FormData

javascript - Fetch API 在 Chrome 中泄漏内存

javascript - 为什么记录 fetch() 的结果 "break"是 ("body stream is locked")?

javascript - 为什么 MongoDB 将时间戳存储为 -1 小时,而不是我计算机上的实际小时