首页 > 解决方案 > 如何使用 JWT Auth 发送 put 请求

问题描述

我正在尝试在我的本地 API 上发送一个 put 请求。我正在使用 JWT 拦截器,它适用于 POST、GET 和 DELETE 请求,但不适用于 PUT,它是未经授权的。

我 console.log 一个 GET 和 PUT 请求,它们都显示令牌就在标题上。

放置请求

{
  "url": "http://localhost:8080/api/tasks/2",
  "body": "",
  "reportProgress": false,
  "withCredentials": false,
  "responseType": "json",
  "method": "PUT",
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": [{
      "name": "Authorization",
      "value": "JWT Token",
      "op": "s"
    }],
    "headers": {},
    "lazyInit": {
      "normalizedNames": {},
      "lazyUpdate": null
    }
  },
  "params": {
    "updates": null,
    "cloneFrom": null,
    "encoder": {},
    "map": {}
  },
  "urlWithParams": "http://localhost:8080/api/tasks/2"
}

获取请求

{
  "url": "http://localhost:8080/api/me",
  "body": null,
  "reportProgress": false,
  "withCredentials": false,
  "responseType": "json",
  "method": "GET",
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": [{
      "name": "Authorization",
      "value": "JWT Token",
      "op": "s"
    }],
    "headers": {},
    "lazyInit": {
      "normalizedNames": {},
      "lazyUpdate": null,
      "headers": {}
    }
  },
  "params": {
    "updates": null,
    "cloneFrom": null,
    "encoder": {},
    "map": {}
  },
  "urlWithParams": "http://localhost:8080/api/me"
}

我发送 put 请求的服务

  updateSchedule(id): Observable<any>{
    let currentUser = this.authenticationService.currentUservalue;

    const httpOptions = {      
      headers:  new HttpHeaders({
          'Authorization': `${currentUser.token}`
    })
  };
    return this.http.put(`${this._url}/tasks/${id}`, httpOptions)
  }

401错误

PUT http://localhost:8080/api/tasks/2 401 (Unauthorized)

如何在 PUT 请求上验证此 JWT?

标签: angulartypescripthttp

解决方案


HttpOptions 是第三个参数,第二个必须是 body。如果没有正文,则放置一个空字符串。见这里https://angular.io/guide/http#making-a-put-request

return this.http.put(`${this._url}/tasks/${id}`,'', httpOptions)

推荐阅读