gpt4 book ai didi

javascript - 发布到 localhost 时 fetch 返回 400

转载 作者:行者123 更新时间:2023-12-01 04:00:02 24 4
gpt4 key购买 nike

我希望在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com