我有一个Angular (版本8)应用程序,它将重定向/调用带有标题的外部url (而不是API)。
我可以调用/重定向外部url,但不能发送任何报头。
事情是这样的,一旦我能够成功登录,我就必须在重定向时将报头中的身份验证令牌发送到外部url。
请告诉我如何在重定向到外部url时发送auth token。
我已经通过了下面的网址,这有助于我重定向到外部网址,但标题不会被发送。
发布于 2021-06-28 14:03:13
我认为这样做的方法是通过XHR请求发送头部。然后,如果你想在之后重新加载,你可以。但是报头传输将首先发生。
this.http
.post('api/login', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe(() => window.location.href='https://some-other-website.com')发布于 2021-06-28 14:48:57
创建headers.的
例如: JSW,如果你在localStorage中有令牌,作为"current_user“令牌:
import { HttpHeaders } from '@angular/common/http';
....
const headers = new HttpHeaders()
.append("Authorization", "Bearer " + localStorage.getItem("current_user")["token"])
.append("Content-type", "application/json");httpOptions。const httpOptions ={ headers: new HttpHeaders({ 'Content-Type':‘应用程序/json’,授权:‘您的身份验证令牌’}) };
或者更整洁(如果您以前已经声明了const headers
const httpOptions = {
headers
}; const externalUrl = 'http://....';
const dataToPut = 'Usually, it will be an object, not a string';
this.http.post<Hero>(this.externalUrl, dataToPut , httpOptions)
.pipe(
catchError(this.handleError('post error: ', dataToPut ))
);无论如何,一旦您知道如何做,在头中发送身份验证令牌的最好方法是通过一个 INTERCEPTOR,,它将拦截所有的调用,并在头中插入身份验证参数:https://angular.io/guide/http#intercepting-requests-and-responses
附言:我强烈建议你阅读这两个官方文档页面,以便进一步研究……更详细的信息都在这里了吗?
https://angular.io/guide/http#adding-headers
角度标头
https://stackoverflow.com/questions/68158144
复制相似问题