Tom el Safadi
Tom el Safadi

Reputation: 6776

Angular 2 HTTP post no HTTP-resource found

I am using Angular 2 in order to send HTTP requests to the server. The server is running with ASP.Net.

My API:

public class LagerController : ApiController
{
    public IHttpActionResult RepHistorie(string vnr, string lagerort)
    {
        ...
    }
}

So I would call the API with

http://123.456.7.89/api/lager?vnr=W17291092373&lagerort=0382691395

This works fine when using a tool called postman with which you can test API's.

But when making a post request with Angular 2, it doesn't work. It says that the HTTP-resource is not found.

Angular 2:

submit() {
  var body = 'vnr=W17291092373&lagerort=0382741400';

  var link = 'http://123.456.7.89/api/lager';
  this.http.post(link, body)
    .subscribe(data => {
      console.log(data);
    }, error => {
      console.log("Oooops!");
    });
}

It seems like the parameters aren't added correctly.

Upvotes: 0

Views: 87

Answers (1)

Vi Elite
Vi Elite

Reputation: 136

This needs clarification, since the API above seems to be a GET Request.

In case it is a POST Request , then you should use the whole URL while running the API

In case you want to submit an object , you should use [FromBody] as a parameter Example

[HttpPost]
public IHttpActionResult( [FromBody]YourObject item ) {

}

==== Client-side

var postUrl = 'http://123.456.7.89/api/lager?vnr=W17291092373&lagerort=0382691395';
var postObject = {};
http.post(postUrl,postObject)

For GET request where you would like to use QueryString

[HttpGet]    
public IHttpActionResult RepHistorie([FromQuery]string vnr,[FromQuery]string lagerort){
                ...
}

====

// Query string can be built using RequestOptionsArgs as well
var builtUrl = 'http://123.456.7.89/api/lager?vnr=W17291092373&lagerort=0382691395';
http.get(builtUrl)

Alternative way is to

var getUrl = 'http://webapi/api/lager';
var requestOptions = {};
http.get(getUrl,requestOptions);

Reference:

Upvotes: 1

Related Questions