【问题标题】:Getting 401 Unauthorized - CORS origin error while posting using HttpClient in Angular5在 Angular5 中使用 HttpClient 发布时出现 401 Unauthorized - CORS 源错误
【发布时间】:2019-05-20 21:47:32
【问题描述】:

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

请在下面找到代码sn-ps:

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,状态文本:“未经授权”,网址: "https://promise-90488.firebaseio.com/data.json", ok: false, …} 错误: {错误:“权限被拒绝”}标头:HttpHeaders {normalizedNames: Map(0),lazyUpdate:null,lazyInit:ƒ} 消息:“Http 失败响应 对于https://promise-90488.firebaseio.com/data.json: 401 未经授权” 名称:“HttpErrorResponse”确定:错误状态:401 statusText: “未经授权”网址:“https://promise-90488.firebaseio.com/data.json原型:HttpResponseBase

【问题讨论】:

  • 我不确定你从哪里得到CORS错误,错误信息显示401,这与授权有关。来自另一个线程:"Receiving a 403 response is the server telling you, “I’m sorry. I know who you are–I believe who you say you are–but you just don’t have permission to access this resource. Maybe if you ask the system administrator nicely, you’ll get permission. But please don’t bother me again until your predicament changes.”
  • CORS 是 BE 错误,而不是前端错误。请发布相关的 BE 内容。
  • this.http.post 将发出一个跨域 JSON 格式的 POST 请求,这需要 CORS 预检 OPTIONS 请求,如果得到 401 响应,则 CORS 请求将失败,因为浏览器没有已获得发出 POST 请求的权限。
  • 为什么说这是一个 CORS 问题?除了标题之外,我在您的帖子中没有看到任何提及

标签: angular typescript cors angular5 angular-httpclient


【解决方案1】:

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

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

【讨论】:

  • 仍然遇到同样的问题
  • 您使用的是什么类型的授权?是不记名令牌吗?
猜你喜欢
  • 2016-03-10
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2021-03-02
  • 2020-10-25
相关资源
最近更新 更多