Jump to content

Angular and Web API


AJBM
 Share

Go to solution Solved by KTachyon,

Recommended Posts

Boas!

Eu quero fazer um pedido a uma Web API, mas não estou a conseguir.

O pedido chega a Web API mas não retorna os dados.

Se eu escrever o endereço diretamente no browser retorna dados, se for pelo javascript dá erro.

public class ClientController : ApiController
{

	// GET: api/Client
	public IEnumerable<string> Get()
	{
		return new string[] {"Teste1","Teste2"};
	}
....
 
(function () {
var app = angular.module("mainApp", []).controller("ClientController", function ($scope, $http) {
	$scope.Clients = ["Ricardo","Maria"];

	$http({
		method: 'GET',
		url: 'http://localhost:60525/api/Client/'

	}).then(function successCallback(response) {
		// this callback will be called asynchronously
		// when the response is available
		$scope.Clients = response.data;
	}, function errorCallback(response) {
		// called asynchronously if an error occurs
		// or server returns response with an error status.
		alert("Erro: " + response);
	});
	$scope.Title = "Titulo";
});
})();
Link to comment
Share on other sites

Coloca um console.log(response) na função successCallback e confirma se os dados chegam ou não.

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Link to comment
Share on other sites

Então, se o alert é executado é porque a API devolveu um código de erro. O que aparece na response? Deves lá ter um statusCode.

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Link to comment
Share on other sites

De certeza que o pedido feito pelo javascript chega à API? No browser também acedes ao localhost:60525?

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Link to comment
Share on other sites

  • Solution

Não sei o que queres dizer com isso.

O mais provável é o teu browser estar a bloquear pedidos cross-domain. Isto se a tua API e o teu frontend estiverem em domínios diferentes. E, mesmo sendo ambos localhost, se tiverem portos diferentes, o domínio é diferente.

Basicamente, o teu browser vai enviar um OPTIONS antes de enviar o GET à API. Se a API não devolver o domínio do frontend no header Access-Control-Allow-Origin (entre outros headers, como o Access-Control-Allow-Methods), o browser não vai tentar fazer o pedido à GET à API.

Se quiseres saber mais sobre o assunto procura por CORS.

Edited by KTachyon

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Link to comment
Share on other sites

Só um detalhe. O Access-Control-Allow-Origin:* não funciona em todos os browsers. Há browsers que querem mesmo que o servidor especifique eu o domínio autorizado é mesmo aquele em que está.

Já tive que resolver este problema e o ideal é tu apanhares o pedido, capturares a origin e devolveres nesse header.

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Link to comment
Share on other sites

Eu apanho o pedido, mas o pedido não têm a propriedade Origin

public class AllowCORS : ActionFilterAttribute
{
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
	 if (actionExecutedContext.Response != null)
	 {
		 base.OnActionExecuted(actionExecutedContext);
		 //Origin???
		 actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
	 }
 }
}

public static class WebApiConfig
   {
    public static void Register(HttpConfiguration config)
    {

	    config.Formatters.Remove(config.Formatters.XmlFormatter);
	    config.Formatters.JsonFormatter.Indent = true;
	    config.EnableCors();
	    // Web API routes
	    config.MapHttpAttributeRoutes();
	    config.Routes.MapHttpRoute(
		    name: "DefaultApi",
		    routeTemplate: "api/{controller}/{id}",
		    defaults: new { id = RouteParameter.Optional }
	    );
    }
   }
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.