gpt4 book ai didi

javascript - 使用 Javascript 进行基本授权 API 登录(CORS?)

转载 作者:行者123 更新时间:2023-12-03 02:45:48 27 4
gpt4 key购买 nike

我读过很多关于尝试使用 Javascript 使用基本授权登录网站 API 的帖子,我觉得我已经尝试了我见过的所有建议,但我无法让它发挥作用。我感觉这可能是一个双重问题,因为我收到了 401 错误和 No Access-Control-Allow-Origin 错误。

有人可以向我解释一下我做错了什么吗?我尝试过以几种不同的方式包含授权,但结果总是相同的。我可以通过 Python 和 Postman 使用基本授权连接到相同的 API,所以不确定为什么 Javascript 对我不起作用。别介意我,我是 Javascript 新手!

这是我的脚本:

function logIn() {
var userName = document.getElementById("username").value;
var pWord = document.getElementById("password").value;
console.log("Your username is: " + userName);
$.ajax
({
type: "GET",
url: "https://example.com",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic " + btoa(userName + ":" + pWord)
},
success: function (){
alert('Thanks for logging in!');
}
});
}

我收到这些错误:

GET https://example.com 401 (Please log in.)

Failed to load https://example.com No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.

最佳答案

您完全正确,CORS 会阻止您使用 API,除非提供商通过“Access-Control-Allow-Origin” header 明确允许。没有办法绕过这个,它是由浏览器安全策略强制执行的。如果可用,请尝试 JSONP。另外,如果这对您有用,我不确定该 API 的用途,您可以使用您的域上托管的某种代理脚本(API 中间人)从您的域下托管的 API 访问远程 API 以传递 CORS。

关于javascript - 使用 Javascript 进行基本授权 API 登录(CORS?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099235/

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