2

It seems to be a bit weird to ask this question, but i could not figure that out.

I have been through stackoverflow links on this and on google and infact tried many of the stuffs, but I could not get the resolution to this. Below are some to mention

Angular 6 HTTP Client Post - Bad request

How to force Angular2 to POST using x-www-form-urlencoded

PROBLEM - request OPTIONS for the api is always 400(bad request)

INSIGHTS -

Below is the code which is working on another project

  const headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded'
  });
  const body = new HttpParams()
    .set('grant_type', 'password')
    .set('username', stateData.username)
    .set('password', stateData.password)
    .set('client_id', 'XXXXX-5B3C-4A7D-WEW-23BWWWF9B7872'); //Letters are dummy here for security reasons

//URL preceded by https
return this.http.post('abc.com/authtoken', body , {headers: headers }).pipe(
  map(res => {
    return res;
  })
 );

Now when I try the same code in another project, it doesnot pass OPTIONS request, throwing 400(Bad request).

we can assume that rest of the stuffs are in order to make this work. The problem mainly is in the code snippet.

The most amazing thing is that when I put a trailing slash in the url like - authtoken/ , it seem to pass the OPTIONS 200OK but fails in the original POST request as 404, quite understandable as the authtoken/ does not exist.

what is the way to go pass that. I am a bit confused as to do what.

As said, I have tried many of the stuffs to make it work. Please suggest

We are using Angular 8.2.13

Thanks

  • Do you have an URL interceptor? if yes , take a look at it, maybe it modifies your request – BELLIL Jan 04 '20 at 18:59
  • @BELLIL : You are absolutely correct. i have HttpInterceptors for Loading and token service. Commenting those worked. Now the question is how to have the interceptors not modifing the request ? –  Jan 06 '20 at 06:40
  • An interceptor modifies automaticall all request, please share your url interceptor code so we can see what it could be done – BELLIL Jan 06 '20 at 09:18

1 Answers1

6
   const headers = new HttpHeaders().set(
     'Content-Type',
    'application/x-www-form-urlencoded;'
   );

   body = 'grant_type=' + password + '&username=' + setData.username + '&password=' + 
   setData.password + '&Client_Id=' + 'XXXXX-5B3C-4A7D-WEW-23BWWWF9B7872';

   return this.http.post('abc.com/authtoken', body , {headers: headers })
Pritish kumar
  • 512
  • 6
  • 13
chandra deep
  • 61
  • 1
  • 5