【问题标题】:Authorization Bearer token is not being sent in Post API Call in Angular 8未在 Angular 8 的 Post API 调用中发送授权持有者令牌
【发布时间】:2019-12-10 05:42:04
【问题描述】:

编辑 2: 我更新代码时忘记返回了...facepalm

编辑:

(将帖子调用更改为:

this._http.post<userArray>(this.apiUrl,users$, httpOptions);

现在它在控制台日志中给了我这个..任何修复?谢谢: https://ibb.co/6PLK71j )

我正在使用邮递员作为我的休息 API。

没有为 POST 调用发送授权令牌,但相同的授权令牌和 HTTP 标头对于 DELETE 调用工作正常。

我的 API: http://dradiobeats.x10host.com/api/areas

(邮递员收藏:https://www.getpostman.com/collections/deb24ed6036451580238

授权令牌: Postman Authorization: Bearer Token.

控制台日志:

Console Log

No Authorization Header is passed

userService.ts

import { Injectable, Input } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { userArray } from "./users.model";
import { Observable } from "rxjs";

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json' ,
    'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImYyOTc3OTBmODc3ODlhYzg3MGE2ZmU3YTY0YzY2YmIwOGU4M2Q0ZmQzY2IyNmNiNWU3NDEzMTFmZjExMDk4NTA5NWUzN2IxN2I5YmI2YmFjIn0.eyJhdWQiOiIyIiwianRpIjoiZjI5Nzc5MGY4Nzc4OWFjODcwYTZmZTdhNjRjNjZiYjA4ZTgzZDRmZDNjYjI2Y2I1ZTc0MTMxMWZmMTEwOTg1MDk1ZTM3YjE3YjliYjZiYWMiLCJpYXQiOjE1NzU4NzM4MzksIm5iZiI6MTU3NTg3MzgzOSwiZXhwIjoxNjA3NDk2MjM5LCJzdWIiOiIyIiwic2NvcGVzIjpbXX0.J3nMXcPpqlRVvIRkrVAMblSUwdlXFmrkn9SPD2WE1DwdiqAMdhay8zAeD550ta9qWiNxHOKMAWF8t3H9cIgItaB9ZX2CxoxzS5P1nJFzit8qxiB-gzJL3mpybrnLtrKGjxsM5i_lBvdJsnhWzi15jKWIu-RNxUYPnXCjuxnXYEiyoJg17hsYUh4910VfFWx4R3WvH7WOvczF53IDKyX5fSTt4WSJUqciuNepkO6Klc8sj_yPmDPQltUjUXSSplkOQ8sL5uHk7PmzSjIfoR8RC0A-YQqI9mbZMTyJ0IyKoAHvRHF8q1cW5qfUmLXTgxcCTmFPqXqIlcAoOoJMCxke5fl0PuK0rgU7dxouATk_3B6cio7-7Zgps0iopDpk2nm-o40mjSiOUGb2kyKckYN09orYuan5wEd1KJ873ejKEgBWOhJu4gQFps8M9VoDXncAqMxeBqbUY1UZENx_n6uduQ_SAY4rgIUFCixfNc5Y_-HLDa108u4-z3APGbdxrhEdZXyHz9xQTaLrWcU_iCJ5g_ObT5VGZHtawZbfOYm2ZZpjPiCZpXunhrsbAcHBX64akWcehmT2gUJqPsxvaObKN3nayML1NHtdZGgAHUE89clhIH610Fod0C_jMTqpU7IkY9aSU781HsQVlHNw3qGbTinWfYPDBG0Lkp9NnmRe9BU' ,
    'Accept' : 'application/json'
  })
};

@Injectable({
  providedIn: "root"
})
export class UsersService {
  users$: userArray[];
  apiUrl = "http://dradiobeats.x10host.com/api/areas";
  delUrl = "http://dradiobeats.x10host.com/api/areas";

  constructor(private _http: HttpClient) {}

  getUsers() {
    return this._http.get<userArray[]>(this.apiUrl);
  }

  deleteUser(id: userArray): Observable<userArray> {
    const url = `${this.apiUrl}/${id}`;
    console.log();
    return this._http.delete<userArray>(url, httpOptions);
  }
  onSubmit(users$: userArray[]): Observable<userArray> {
    console.log(users$);
    return this._http.post<userArray>(this.apiUrl, httpOptions);
  }
}

Add-Post.ts

import { Component, OnInit } from "@angular/core";
import { UsersService } from "src/app/users.service";

@Component({
  selector: "app-add-posts",
  templateUrl: "./add-posts.component.html",
  styleUrls: ["./add-posts.component.css"]
})
export class AddPostsComponent implements OnInit {
  name: string;
  description: string;
  domain: string;
  picture: string;
  id: number = 29;
  constructor(private userService: UsersService) {}

  ngOnInit() {}

  onSubmit() {
    const users$ = {
      name: this.name,
      description: this.description,
      domain: this.domain,
      picture: this.picture
    };
    this.userService.onSubmit(users$).subscribe();
  }
}

有人可以帮我解决这个问题吗?谢谢。 c:

【问题讨论】:

  • 在 Post 请求中,第一个参数是 API URL,第二个是 body,第三个是 httpOptions,你发送的 httpOptions 是 body,make 是第三个。它应该看起来像这样: return this._http.post(this.apiUrl, {},httpOptions);

标签: javascript angular angular8


【解决方案1】:

使用this._http.post&lt;userArray&gt;(this.apiUrl, data , httpOptions);

第二个参数是你需要传递的数据

【讨论】:

【解决方案2】:

使用角度拦截器将令牌添加到每个请求。

import { Injectable } from '@angular/core';

import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse
} from '@angular/common/http'
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';


@Injectable()

export class ApiHeaderInterceptor implements HttpInterceptor {

  constructor() { }

  // intercept request and add token
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const bearer = 'Bearer eyJ0eXAiOiJKV1QiLCJh.....'; // this.anyService.getToken();

    if (bearer) {
      request = request.clone({
        setHeaders: {
          'Authorization': bearer,
        }
      });
    }

    return next.handle(request)
      .pipe(
        tap(event => {
          if (event instanceof HttpResponse) {
          }
        }, error => {
          // Hadle Errors
        })
      );

  };
}

像这样将它添加到您的 app.module 提供程序中

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ApiHeaderInterceptor, multi: true },
],

【讨论】:

    【解决方案3】:

    onSubmit() 后调用中缺少您的请求正文。

    this._http.post(<url>, <request body>, <headers>);
    

    【讨论】:

      【解决方案4】:

      试试这个: this._http.post&lt;userArray&gt;(this.apiUrl, requestData , httpOptions);

      post 中的第二个参数是一个请求对象,没有对象你不能发送 post 请求

      【讨论】:

        【解决方案5】:

        我认为你的发帖请求应该是这样的

        this._http.post<userArray>(this.apiUrl,users$, httpOptions);
        

        您将httpOptions 作为第二个参数传递,但它应该是发布请求的第三个参数。第二个参数应该是body。

        喜欢这个

        post(url: string, body: any, options:....
        

        参考他们的DOC for more details

        同样在你调用onSubmit服务方法的组件中 通过传递单个用户但服务期望用户数组。所以你必须像下面这样更改服务onSubmit 方法签名。所以我也会期待一个用户。

         onSubmit(users$: userArray)
        

        【讨论】:

        • 现在它在控制台日志中给了我这个..任何修复?谢谢ibb.co/6PLK71j
        • Observable&lt;userArray&gt; 这个问题如果您没有类型,请尝试使用Observable&lt;any&gt;。订阅也应该这样this.userService.onSubmit(users$).subscribe((data)=&gt; { // do something here })
        • 您是否返回了用户数组,然后尝试使用Observable&lt;Array&lt;userArray&gt;&gt;
        • 问题与您的onSubmit(users$: userArray[]) 您使用this.userService.onSubmit(users$) 与一个用户但onSubmit 方法期望用户数组请将服务方法更改为 onSubmit(users$: userArray)`
        • 将其更改为 onSubmit(users$: userArray) 但仍然没有运气.. 谢谢
        猜你喜欢
        • 1970-01-01
        • 2021-08-29
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-30
        • 2019-03-15
        • 2019-08-07
        相关资源
        最近更新 更多