Ionic: My http.post to WebApi RestFull doesn't work - javascript

I'm developing an app with Ionic Framework and I'm changing some of the information with my web service API RestFull. When I connect with a GET method it works, but when I try to connect with a POST method it doesn't work.
This is the code of Ionic:
import { HttpClient ] from '#angular/common/http';
constructor(private http: HttpClient ...)
And this is the function (I am returning a promise):
var user = {"nom" : "whatever", "password" : "whatever2"};
var options = { headers: {'Content-Type': 'application/json; charset=utf-8;'}};
return this.http.post(myLink, user, options).toPromise();
In Web Service, the code is (C#):
[Route("AuthFullUser")]
[HttpPost]
public HttpResponseMessage login([FromBody]User user){
var u = UserRepository.login(user.nom.ToString(), user.password.ToString());
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, u);
return response;
}
If I try to enter from Ionic doesn't work, but with PostMan (an app) it works.
On the other hand, if I put [HttpOptions] above the [Route("AuthFullUser")] I am able to access the web service but the parameters are NULL.
I tried to make a request with $.ajax{} or $.post{} but neither worked.
I tried to add on my headers:
"Acces-Control-Allow-Origin" : "*",
"Acces-Control-Allow-Credentials" : "true",
"Acces-Control-Allow-Methods" : "GET, POST, PUT, DELETE, OPTIONS",
"Acces-Control-Allow-Headers" : "Content-Type"
But neither worked.
I have been struggling for weeks on this. Any help would be greatly appreciated.

If someone is having the same trouble I found the solution.
It was all from the Web Service and his headers.
You only need to allow all the headers, it's all on the documentation.
If someone have a question, they can put it here and i will try to give my best answer.

Related

Laravel api returns value in postman but returns empty array in Vue js

I have a small Api built in laravel that is supposed to return a response when an endpoint is hit.
The problem is, that same end point returns something in postman but returns empty data in Vue Js.
I have been battling this for 48 hours now, and is driving me insane, any help will be appreciated.
Thank you
public function search_passport(Request $request){
$pass = DB::table('passengers')->where('passport_number',$request->input('passport_number'))->get();
if($pass->count() == 0){
return response(['message' => 'Passport number not found, please fill the form']);
}
return new PassengerResource($pass);
}// search_passenger
Above is the code from the controller in the Api
Route::post('/searchpassport', [PassengerController::class, 'search_passport']);
And this is the route
this.$http.post('searchpassport', this.passport_number, {headers:{
'Authorization' : 'Bearer ' + this.token.access_token,
'Accept' : 'application/json',
'Content-Type' : 'application'
}})
.then(res => {
console.log(res)
})
This is also the API call am making in the Vue Js
Assuming this.$http is Axios and this.passport_number is a string, you're missing the field / property name for the request payload, ie "passport_number". Also, your Content-type header is incorrect.
Try this instead
this.$http.post("/searchpassport", {
passport_number: this.passport_number
}, {
headers: {
Authorization: `Bearer ${this.token.access_token}`
}
})
You do not need to supply the Accept or Content-type headers. The defaults will be sufficient.
It's good practice to use your browser's developer tools for debugging. The Network tab in particular is great for checking the headers and data sent in your HTTP requests and the responses you get back.

How can I test my web api Post Web method to know what's going on inside?

So here's my situation...
We have an on-prem installation of Microsoft Dynamics CRM and I am trying to make an ajax call from it to a service I created on another one of our servers. There have been many issues already that I've solved - but I'm able at this point to successfully make a GET request to my service from CRM via javascript I've put on a form in CRM.
Just for reference (because I'm not entirely sure at this point if these things are related or not)...
I had to set anonymous authentication in IIS for my service (CRM has
its own authentication that I will be relying on)
I had to set a response header of Access-Control-Allow-Origin with the host address of our CRM installation
So, after doing those things I was able to successfully call my web service via GET. I could return back a string I had from a [HttpGet] web method.
But, now I need to actually call a web method via POST to post some data to my web service. So, below you can see my implementation for the service as well as the javascript I'm using the make the POST call.
using CRMService.Models;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Http;
namespace CRMService.Controllers
{
public class DefaultController : ApiController
{
// GET: Default
public string Get()
{
return "Hi";
}
[HttpPost]
public string GiveParameters(TestClass tc)
{
try
{
Dictionary<string, object> Parameters = new Dictionary<string, object>();
Parameters.Add("id", tc.id);
Parameters.Add("one", tc.one);
Parameters.Add("two", tc.two);
NonQuery("InsertTestItem", ConfigurationManager.ConnectionStrings["TestConnection"].ToString(), Parameters);
return "success";
}
catch (Exception ex)
{
return "ex";
}
}
}
}
var new_budget = Xrm.Page.data.entity.attributes.get("new_budget").getValue();
var new_name = Xrm.Page.data.entity.attributes.get("new_name").getValue();
var id = Xrm.Page.data.entity.getId();
data = '{"TestClass":{"one":"' + new_name + '", "two":"'+ new_budget +'", "id":"'+ id +'"}}'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "https://<hiddingMyUrl>/api/Default/GiveParameters",
data: data,
dataType: "json",
success: function(data) {
console.log("Success");
},
error: function(result) {
console.log("Error");
}
});
When I make this POST call, at first I could see it was doing some "preflight" stuff and making an OPTIONS request - then returning a 403 (I think, if memory serves me right). I looked that up and solved that issue by adding a Access-Control-Allow-Headers header to my web service in IIS with the value of Origin, X-Requested-With, Content-Type, Accept
After doing that my POST actually gives a 200 status code - but, as you can see in my code, I should then be seeing data in a database if everything went well.
..So of course then the question is... is my web service code working properly? And normally I could test for that easily - however I am fairly new to web api. I don't really get the best way to testing at this point - and I don't know if it's something with my code specifically or if there is some configuration issue with web api itself.
Here is my routeconfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
You should try working with a REST client.
Here are two nice ones :
Advanced Rest Client
Postman
I personally prefer Postman but really both are good.

Cors issue API not on same server

I'm using Web API 2. in my WebApiConfig, I have this.
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var origin = WebConfigurationManager.AppSettings["origin"];
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
}
Register Method
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
EnableCrossSiteRequests(config);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new ErrorHandler());
}
From my understanding shouldn't that all I need to for this to work? It's worked on my dev computer when they are hosted together. But now one is on a web server and the API is on a different web server.
I'm getting - Origin ... not found in Access-Control-Allow-Origin header.
I have it set to allow all Origin. I've tried adding it in the web config , and other methods posted around Stack overflow. I don't understand why its being denied?
Front end is Angular, using Ngresource for requests.
If I use the Network Tab in chrome dev tools, the Response to the request is 200 OK, and nothing else happens after that. Been searching all day for solutions, nothing I've tried so far has worked.
Thank you.
From my understanding shouldn't that all I need to for this to work?
Nope. You should decorate the Web API controllers/actions that you would like to be calling cross domain with the [EnableCors] attribute:
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class MyController: ApiController
{
...
}
Here's a good read on this topic.

Calling a Web Api 2 Method using Ajax

I have a Web Api 2 project which I used for a mobile project. I am trying to use the same api's for a web project but am unable to reach them using ajax. I've confirmed that my url is correct and I am able to hit the endpoint from an android project and from fiddler. Am I missing something is my ajax call? I always hit the error function, which returns 'undefined'. I can set a breakpoint in my webapi project and that endpoint is never being hit.
// GET: api/Trips
public IQueryable<Trip> GetTrips()
{
return db.Trips.Include("Users");
}
jquery
$.ajax({
url: 'http://localhost:49669/api/Trips',
type: 'GET',
contentType: 'application/json;charset=utf-8',
success: function (data) {
alert("success!!");
},
error: function (x, y) {
alert(x.response);
}
});
You may need to enable CORS if trying to hit your API form a browser.
Step 1, modify your WebApiConfig file (App_Start/WebApiConfig.cs):
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Add this line
config.EnableCors();
// the rest of your code
}
}
}
Step 2, add the [EnableCors] attribute to your Web API controller:
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MyApp.Controllers
{
[EnableCors(origins: "http://www.whatever.net", headers: "*", methods: "*")]
public class HelloWorldController : ApiController
{
// GET: api/Trips
public IQueryable<Trip> GetTrips()
{
return db.Trips.Include("Users");
}
}
}
**Note: ** You may also need to install the CORS nuget package.
Install-Package Microsoft.AspNet.WebApi.Cors
contentType is for the content type beint sent to the server; this is the only possible reason I can imagine your code not working since you said it's never actually making the request so it must be some error handling done by jQuery before making the request, and the error is being thrown because you are trying to specify contentType for a GET request.
The property for specifying a response type is dataType. Try changing contentType to dataType?

XMLHttpRequest cannot load URL. Invalid HTTP status code 400

I have WebApi Application and one MVC5 Applicatiion.I am sending request to webApi using angularJS from MVC5 Application.But it is not working fine when I send DELETE or POST request. I am getting 'XMLHttpRequest cannot load URL. Invalid HTTP status code 400' error in Browser.But it is working fine for GET request.See the below code.
Sevice call
$http.delete("http://localhost:8643/api/values/1");
WebApi
// DELETE api/values/5
[HttpDelete]
public void Delete(int id)
{
var emp = employees.FirstOrDefault(x => x.ID == id);
if(emp!=null)
{
employees.Remove(emp);
}
}
Even I have enabled Cors in my WebApi.
Can anyone please help me.
For the post try to add $.param to your object, and specify the content type.
Something like that.
$http({
method: "POST",
url: "http://localhost:8643/api/values",
data: $.param({'Type': 'Type', 'Name': 'Name'}),
headers: {'Content-Type': 'application/x-www-form-urlencoded',}
})
Hope this might help.
As for Delete and Put, I am still having problems with them myself.

Categories

Resources