Tobias Moe Thorstensen Tobias Moe Thorstensen - 6 months ago 45
Node.js Question

New to Typescript & Angular problems with Http Post

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

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

var request = require("request");

var options = { method: 'POST',
url: 'http://localhost:8081/login',
{ '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);


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, content, {headers: headers})
.map((response:Response) => {

let token = response.json() && response.json().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?

Answer Source

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);
    ....., body).map(..)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download