2
votes

I'd like to update data with using PUT Method on my angular service and express routes, but it give me 401 error. This is my service :

//401
makeAdmin(_id) {
  this.loadToken()
  let headers = new Headers()
  headers.append('Authorization', this.authToken)
  console.log(_id)
  headers.append('Content-Type', 'application/json')
  return this.http.put(this.baseUri+'users/makeAdmin/'+_id,{headers: headers})
    .map(res => res.json())
}

But when I'm using GET or DELETE Method, it can send data to my express routes. This is my express route :

router.put('/makeAdmin/:id',passport.authenticate('jwt', {session:false}),(req, res, next)=>{
    console.log(req.params.id)
})

My browser log error :

PUT http://localhost:8080/users/makeAdmin/5b57219f1e1be6279c95a5be 401 (Unauthorized) core.js:1440 ERROR Response {_body: "Unauthorized", status: 401, ok: false, statusText: "Unauthorized", headers: Headers, …}

EDITED This is from console.log :

Response {_body: "Unauthorized", status: 401, ok: false, statusText: "Unauthorized", headers: Headers, …} headers : Headers {_headers: Map(0), _normalizedNames: Map(0)} ok : false status : 401 statusText : "Unauthorized" type : 2 url : "http://localhost:8080/users/makeAdmin/5b57219f1e1be6279c95a5be" _body : "Unauthorized" proto : Body

2

2 Answers

2
votes

try:

let headers = new Headers().append('Authorization', this.authToken);

From the HttpHeaders docs: Immutable set of Http headers, with lazy parsing.

https://angular.io/api/common/http/HttpHeaders

2
votes

Since you are using map and Headers instead of HttpHeaders, I assume that you are using angular's old Http client, instead of the new HttpClient class.

The PUT method needs a body (documentation), so try this

return this.http.put(this.baseUri+'users/makeAdmin/'+_id, null, {headers: headers})
.map(res => res.json())

If you don't specify null as the body, then the headers are sent as the body parameter, and the options parameter with the actual headers is left empty.