我下面的 fetch 语句在我的 .ts 文件中运行良好。
const fileResult = await fetch(environment.stripeFileUrl, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + environment.stripePublishableKey
},
body: data,
});
const fileData = await fileResult.json();
但是当我像下面这样写时,我得到一个状态 401,状态文本正常,但是一个错误,表明我的 API 密钥不正确。 我是否错误地插入了标头?
新代码不起作用
this.accountService.getStripeIdentityToken(data).subscribe(response => {
if (response.error) {
this.showError(response.error.message);
} else {
this.outputFile.emit({
file: response.id,
description: null
});
}
}, error => {
console.log(error);
}).add(() => {
this.loading(false);
});
getStripeIdentityToken(data: any) {
let headers = new HttpHeaders();
headers = headers.set('Authorization', `Bearer ${environment.stripePublishableKey}`);
// I also tried below with same error about the incorrect API key
// headers = headers.set('Authorization', `Bearer pk_test_fTr...BVLn9e6`);
return this.http.post<any>(environment.stripeFileUrl, data, {
headers
});
}
在您的
JwtInterceptor
中,您可以检查并使用包含“授权”密钥对的现有请求标头。
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Get default auth token from the service.
const authToken = /* Default token from service/local storage etc. */
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = req.clone({
headers: req.headers.set('Authorization',
request.headers.get('Authorization') ?? authToken)
});
// send cloned request with header to the next handler.
return next.handle(authReq);
}
}