我正在开发一个带有 Angular 的 Web 应用程序,该应用程序向我的 Azure API 发送请求。 API 受 Angular 保护。当我在浏览器中调用该网址时,我会被重定向到微软登录页面。登录后我回到 API。
现在,我想从我的 Angular 应用程序向 API 发送请求:
const auth = btoa("[my username]:[my password]");
headers = {"Authorization": "Basic " + auth};
$http.get("http://[webapp name].azurewebsites.net/api/contacts", {headers: headers}).then(function (response) {
console.log("!!!LoggedIn!!!");
});
我将 [webapp name].azurewebsites.net 添加到了 azure 门户中的 CORS。 当我执行此操作时,出现错误:
[Error] Failed to load resource: the server responded with a status of 400 (Bad Request)
[Error] Failed to load resource: Preflight response is not successful
[Error] XMLHttpRequest cannot load http://[webapp name].azurewebsites.net/api/contacts
azurewebsites.net/api/contacts。预检响应未成功
知道如何修复它吗?
更新
我用这段代码再次尝试:
const auth = btoa("[my username]:[my password]");
var config = {headers: {
'Authorization': 'Basic ' + auth,
"Origin": "http://[webapp name].azurewebsites.net/api/contacts",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "X-Custom-Header"
}
};
$http.get("http://[webapp name].azurewebsites.net/api/contacts", config).then(function (response) {
console.log("!!!LoggedIn!!!");
});
现在我收到这些错误:
Refused to set unsafe header "Origin"
Refused to set unsafe header "Access-Control-Request-Method"
Refused to set unsafe header "Access-Control-Request-Headers"
Response to preflight request doesn't pass access control check: 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 400
当我删除这些“不安全 header ”时,最后一条错误消息仍然存在。
为什么Origin自动为null?
最佳答案
您应该在服务器/后端代码中的 CORS 中添加请求站点 URL 的地址。每种语言或框架可能都有自己的添加方式,尝试在 google 中搜索“[后端语言] cors”(例如“C# cors”)。 (感谢 @Gary Liu - MSFT)
您可以通过检查开发人员控制台中的网络选项卡来确认您已添加正确的源。
关于angularjs - 预检响应不成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40359565/