1

I'm new to Angular and Typescript and I try to create a simple login page. I've created a service in typescript which is invoked when the user presses the 'Login' button. The textboxes which contains the username and password is bound correctly to the model, but when I send the request to my backend written in C#, it will not hit the breakpoint which I suspect is because of the format of the message being sent on the wire.

So using PostMan, I'm able to invoke the service and get back an access_token When exporting the request to code in PostMan this is what the NodeJS variant look like:

var request = require("request");

var options = { method: 'POST',
  url: 'http://localhost:8081/login',
  headers: 
   { 'postman-token': '34dd4d0f-ff16-db4f-ebae-dab945729410',
     'cache-control': 'no-cache',
     'content-type': 'application/x-www-form-urlencoded' },
  form: { username: 'test', password: 'test', grant_type: 'password' } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

And this is my Typescript code

login(userName: string, password:string) : Observable<boolean> {

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded')

        var content = JSON.stringify({
            username: userName, 
            password: password,
            grant_type: this.grant_type
        });

        return this.http.post(this.authenticationEndpoint, content, {headers: headers})
                .map((response:Response) =>  {

                    let token = response.json() && response.json().token;
                    if(token){
                        //this.token = token;
                        localStorage.setItem('user', JSON.stringify({userName: userName, token:token}));
                        return true;
                    }

                    return false;
                });        
    }

This results in an error in Visual Studio Code, which says:

enter image description here

I'm not really sure how I should interpret this error message, but since the method in my webservice is not invoked I'm pretty sure that it has something to do with the HTTP headers or the format of the Http Post.. Any ideas?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143
  • I'm guessing your are using Angular 4.3.4? Hard to tell. I think you don't have to JSON.stringify your content. Why are you using 'application/x-www-form-urlencoded' content type? – ChrisY Aug 20 '17 at 13:32
  • what is that postman token do you need to set it up ? – Rahul Singh Aug 20 '17 at 13:38
  • @ChrisY According to my package.json the @angular/core is set to ^4.2.4 which according to my understanding mean "all above this version"? Is there any other concrete way to check the version? Thanks! – Tobias Moe Thorstensen Aug 20 '17 at 13:38
  • @RahulSingh I guess I dont need it, probably something Postman adds automatically. – Tobias Moe Thorstensen Aug 20 '17 at 13:38
  • For content type 'application/x-www-form-urlencoded' the request body should look like `parameter=value&also=another` – ChrisY Aug 20 '17 at 13:39
  • @ChrisY I see, so it's wrong to format it as Json.. – Tobias Moe Thorstensen Aug 20 '17 at 13:40
  • 1
    You need to serialize it yourself to a string. using `URLSearchParams` .Tell me if you need an answer – Rahul Singh Aug 20 '17 at 13:44
  • 1
    guess so. you could try to use 'let content = `username=${userame}&password=${password}`; see: https://stackoverflow.com/questions/39863317/how-to-force-angular2-to-post-using-x-www-form-urlencoded – ChrisY Aug 20 '17 at 13:45

1 Answers1

1

Using URLSearchParams as the body of the request and angular will automatically set the content type to application/x-www-form-urlencoded

import { URLSearchParams } from "@angular/http"

    let body = new URLSearchParams();
    body.set('username', username);
    body.set('password', password);
    .....


this.http.post(this.authenticationEndpoint, body).map(..)
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • 1
    @TobiasMoeThorstensen as you are new a quick thought try and use the new [HttpClient](https://angular.io/guide/http) instead of http its has been deprecated in Angular latest release – Rahul Singh Aug 20 '17 at 13:50
  • Thanks for the heads up! At least it breaks in my C# code, but when returned to typescript code, it give me this error: ERROR Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers, …} _body:ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, …} headers:Headers {_headers: Map(0), _normalizedNames: Map(0)} ok:false status:0 statusText:"" type:3 url:null __proto__:Body {constructor: , toString: } – Tobias Moe Thorstensen Aug 20 '17 at 13:53