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

时间:2018-12-20 11:12:22

标签: angular typescript cors angular5 angular-httpclient

尝试将数据发布到我的后端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)
      );

错误消息如下:

  

POST https://promise-90488.firebaseio.com/data.json 401(未经授权)   app.component.ts:37 HttpErrorResponse {标头:HttpHeaders,状态:   401,statusText:“未经授权”,URL:   “ https://promise-90488.firebaseio.com/data.json”,确定:错误,...}错误:   {错误:“权限被拒绝”}标头:HttpHeaders {normalizedNames:   Map(0),lazyUpdate:空,lazyInit:ƒ}消息:“ Http失败响应   for https://promise-90488.firebaseio.com/data.json:401未经授权”   名称:“ HttpErrorResponse”,确定:错误状态:401 statusText:   “未经授权”的网址:“ https://promise-90488.firebaseio.com/data.json”    proto :HttpResponseBase

1 个答案:

答案 0 :(得分:0)

似乎您没有随请求传递授权标头

const httpOptions = {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token'
  })
};

return this.http.post('https://promise-90488.firebaseio.com/data.json', users, httpOptions);

查看文档here以获得更多详细信息

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

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);
  }
}

您可以了解有关拦截器here

的更多信息