获取401未经授权-在Angular5中使用HttpClient发布时出现CORS源错误



在尝试将数据发布到我的后端firebase数据库时出现以下错误。

请在下面找到代码片段:

storeUsers(users: any[]){
return this.http.post('https://promise-90488.firebaseio.com/data.json', users);
}

appcomponent.ts:

const result = Object.assign({}, this.userForm.value );
console.log(result);
this.userService.storeUsers(result)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);

错误消息如下:

POSThttps://promise-90488.firebaseio.com/data.json401(未经授权(app.component.ts:37 HttpErrorResponse{headers:HttpHeaders,状态:401,状态文本:"未经授权",网址:"https://promise-90488.firebaseio.com/data.json",ok:false,…}错误:{error:"Permission denied"}标头:HttpHeaders{normalizedNames:Map(0(,lazyUpdate:null,lazyInit:ƒ}消息:"Http失败响应对于https://promise-90488.firebaseio.com/data.json:401未经授权"name:"HttpErrorResponse"ok:false状态:401状态文本:"未经授权"url:https://promise-90488.firebaseio.com/data.json">proto:HttpResponseBase

似乎您没有将授权标头与请求一起传递

const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'my-auth-token'
})
};
return this.http.post('https://promise-90488.firebaseio.com/data.json', users, httpOptions);

查看此处的文档以了解更多详细信息

要在所有请求中包含授权标头,您可以实现一个拦截器:

import { AuthService } from '../auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Get the auth token from the service.
const authToken = this.auth.getAuthorizationToken();
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = req.clone({
headers: req.headers.set('Authorization', authToken)
});
// send cloned request with header to the next handler.
return next.handle(authReq);
}
}

你可以在这里阅读更多关于拦截的信息

最新更新