在我的 Angular 2 应用程序中,我尝试使用密码和用户名凭据登录到我的后端服务器。到目前为止,Chrome 和 Safari 在运行我的应用程序和登录时没有遇到任何问题。今天我第一次尝试在 Microsoft IE Edge 中运行该应用程序。但是,当我尝试登录时,出现以下错误:
SEC7123:Request header Authorization was not present in the Access-Control-Allow-Headers list.
我正在使用 angular 2+ 来运行 http 请求。下面是我的登录功能。任何想法修复可能是什么?
loginHttp(username: string, password: string): any {
let headers: any = new Headers();
let data: any = null;
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this.http.post(this.authService.getUrl()+ '/login', data, {headers: headers})
.map(res => res.json());
}
更新
检查后端(我们使用 Symphony),我们确实在标头中包含了 CORS:
defaults:
allow_origin: ["%cors_allow_origin%"]
allow_methods: ["GET", "POST", "PUT", "DELETE", "LINK", "UNLINK"]
allow_headers: ["Content-Type", "Authorization", "X-Employee-Id"]
max_age: 3600
paths:
'^/': ~
解决
最终的问题与 Symphony 有关。我们使用了 nelmio cors 配置,但它没有设置标题。无论如何都可以工作。
确保您允许 CROS
res.setHeader('Access-Control-Allow-Origin', '*');
// methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
注意:我在这个例子中使用 Express。
该文件修改一下。希望能帮助到你。
更新:
在使用 Symfony 之前,我们遇到了同样的问题。我找到的解决方案是:
OPTIONS
方法,允许 CROS这是我的意思的图像:
RestListner 的代码:
class RestListener
{
/**
* Constructor
*/
public function __construct()
{
}
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest())
return;
$responseHeaders = $event->getResponse()->headers;
$responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept, x-wsse, set-cookie, x-sessid');
$responseHeaders->set('Access-Control-Allow-Origin', '*');
$responseHeaders->set('Access-Control-Expose-Headers', '*');
$responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
$request = $event->getRequest();
$method = $request->getRealMethod();
if (strtoupper($method) === 'OPTIONS') {
header('Access-Control-Allow-Headers: origin, content-type, accept, x-wsse, set-cookie, x-sessid');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Expose-Headers', '*');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
die(json_encode(array(
'message' => 'Accepted',
'status' => 202,
)));
}
}
}
我们使用 symfony 作为后端,使用 Angular 2.x 作为前端。
有了解决方案,CROS 就通过了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句