Click here to Skip to main content
15,844,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing AngularJS2 with Restful web API , and getting some console errors while calling HTTP post. Errors are listed below,
Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
XMLHttpRequest cannot load http://localhost:64336/api/User/UserLogin. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:51663' is therefore not allowed access.
EXCEPTION: Response with status: 0  for URL: null

Hope you help

What I have tried:

I enabled cors in web API like
web API CONFIG
public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
           // Web API configuration and services
           config.EnableCors();

           // Web API routes
           config.MapHttpAttributeRoutes();

           config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
       }

Controller
[EnableCors(origins: "http://localhost:64336", headers: "*", methods: "*")]
   public class UserController : ApiController
   {
       public HttpResponseMessage UserLogin([FromBody] LoginRequestData objValidate)
       {
           UserModelManager _UserModelManagerr = new Models.UserModelManager();

           return Request.CreateResponse(HttpStatusCode.OK, _UserModelManagerr.Login(objValidate), GetJSONFormatter());

       }


AngularJS Application
login(username: string, password: string) {
         let toAdd = JSON.stringify({ Email: username, password: password });
       var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        return this._http.post(this._apiUrl,
            toAdd,
            { headers: headers })
            .map((response: Response) => <user>response.json()); 
    }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900