gpt4 book ai didi

Angular 4 : unable to read headers from response - not a CORS issue

转载 作者:太空狗 更新时间:2023-10-29 18:08:04 25 4
gpt4 key购买 nike

在服务器自动更新 token 的情况下,我在基础知识上苦苦挣扎:从响应中获取 header 数据。

它似乎与 CORS 无关,因为我的 Node/express allwos Authorization/x-access-token 并相应地做出响应(参见下面的网络选项卡屏幕截图)。

我希望看到工作的第一步只是从响应中读取 header 。查看我的代码,它是在文档中找到的样板。获取“Content-Length”的事件返回 null。

auth-service.ts

login(username:string, password:string):Observable<boolean>{
this.loggedIn = false;
return new Observable( (observer:Observer<boolean>) => {

const body = {user: username, pwd: password};
const url = this.config.API_ENDPOINT_PUBLIC_AUTH;

this.httpClient.post(url, body, {
responseType: 'text',
observe: "response"
}).first().subscribe(
(response:HttpResponse<string>) => {

// DEBUG
console.log(response.headers.get('Authorization'));
console.log(response.headers.get('X-Test-Header'));
console.log(response.headers.get('Content-length'));


this.token = response.headers.get('Authorization');
this.storeToken(this.token);
this.currentUser = username;
this.loggedIn = true;
this.authChanged$.next('auth');
observer.next(true);
},
(err) => observer.next(false),
() => {},
);
});
}

控制台输出:

null

null

null

将此与此请求的我的网络选项卡的内容进行比较:

enter image description here

不用说我的 HttpInterceptor 也不起作用 - 在响应中提供“授权” header 后,它使用该值作为新 token 。这是为了实现 token 的自动更新:

token.interceptor.ts

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

const authService = this.injector.get(AuthService);
const token = authService.getToken();

if(token){
request = request.clone({
setHeaders: { 'x-access-token' : token }
});
}

return next.handle(request).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
const response:HttpResponse<any> = (<HttpResponse<any>> event);
const authorizationHeader = response.headers.get('Authorization');
console.log('Authorization header value: ' + authorizationHeader);
if(authorizationHeader){
authService.setToken(authorizationHeader);
}
}
},
(err: any) => {
if (err instanceof HttpErrorResponse){
if (err.status === 401) {
this.router.navigate(['/']);
}
}
});
}

最佳答案

好的,这就是答案:我使用 Node.js/Express 作为后端,即使 header 在 Chrome 的网络选项卡中可见,它也无法让 Angular 处理它们。

“怎么看得见却不能用?”我还是不清楚。

配置您的 Node/Express 应用(查找评论“SOLUTION HERE”):

function configureExpress(expressApp){  
expressApp.use(bodyparser.urlencoded({ extended: true }));
expressApp.use(bodyparser.json());

// Middleware: Use CORS, add headers and allow methods
expressApp.use(expressMiddleware);
}

function expressMiddleware(req, res, next) {

// Request origin: Allow ALL
res.header("Access-Control-Allow-Origin", "*");

// Allowed headers
res.header("Access-Control-Allow-Headers",

"Origin"
+",X-Requested-With" // Dont allow AJAX CORS without server consent - see http://stackoverflow.com/questions/17478731/whats-the-point-of-the-x-requested-with-header
+",x-access-token"
+",Content-Type"
+",Authorization"
+",Accept"
);

// SOLUTION HERE
// Allow headers access
res.header("access-control-expose-headers",
",Authorization"
+",Content-Length"
);

// Allowed methods
res.header('Access-Control-Allow-Methods',
'GET,'
+',POST'
+',OPTIONS'
+',PUT,'
+',DELETE'
);

// Handle CORS requests: cross-domain/origin requests will begin with an OPTION request to the same endpoint.
if('OPTIONS' === req.method){
res.sendStatus(200);
}

else{
// Request validations complete
next();
}
}

关于 Angular 4 : unable to read headers from response - not a CORS issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47155983/

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