使用Javascript进行基本授权API登录(CORS?)
我已经阅读了许多关于尝试使用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’标题明确允许。 没有办法绕过这个,它是由浏览器安全策略强制执行的。 如果可用,请尝试JSONP。 此外,如果这对您有用,我不确定API的作用,您可以使用托管在您的域上的某种代理脚本,API中间人从您域下托管的API访问远程API以传递CORS。
- 不能让CORS在chrome和firefox中工作
- 请在401时帮助测试Firefox jQuery ajax中的CORS问题
- 基于jQuery AJAX SOAP的Web服务和CORS(跨域资源共享)
- 使用Javascript但不使用Python / PHP的CORS错误
- CORS问题:获取错误“No’Access-Control-Allow-Origin’标题存在”实际存在时
- 读取和解析unicode json数据在IE和FF中不起作用
- IE8 / IE9中的跨源头
- Jquery AJAX:请求的资源上没有“Access-Control-Allow-Origin”标头
- Angular $ http.delete CORS错误(预检请求)