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?

8
  • 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? Commented Aug 20, 2017 at 13:32
  • what is that postman token do you need to set it up ? Commented Aug 20, 2017 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! Commented Aug 20, 2017 at 13:38
  • 1
    You need to serialize it yourself to a string. using URLSearchParams .Tell me if you need an answer Commented Aug 20, 2017 at 13:44
  • 1
    guess so. you could try to use 'let content = username=${userame}&password=${password}; see: stackoverflow.com/questions/39863317/… Commented Aug 20, 2017 at 13:45

1 Answer 1

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(..)
Sign up to request clarification or add additional context in comments.

2 Comments

@TobiasMoeThorstensen as you are new a quick thought try and use the new HttpClient instead of http its has been deprecated in Angular latest release
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: }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.