0

Gettting below error when trying $http.post from anugular js to asp.net web api

angular.js:10722 OPTIONS //localhost:54681/api/AccessToken/Generate (anonymous function) @ angular.js:10722sendReq @ angular.js:10515serverRequest @ angular.js:10222processQueue @ angular.js:14745(anonymous function) @ angular.js:14761$eval @ angular.js:15989$digest @ angular.js:15800$apply @ angular.js:16097(anonymous function) @ angular-touch.js:477dispatch @ jquery.js:4435elemData.handle @ jquery.js:4121 index.html#/access/signin:1 XMLHttpRequest cannot load

http://localhost:54681/api/AccessToken/Generate. Response for preflight has invalid HTTP status code 404

My web api is running on //localhost:54681/ and my angular application running on //localhost:62319/

1 - Angular $http.post ajax method on //localhost:62319/

/// <reference path="../../../libs/angular/angular/angular.js" />
'use strict';

app.controller('SigninFormController', ['$scope', '$http', '$state', function ($scope, $http, $state) {
    $scope.user = {};
    $scope.authError = null;
    $scope.login = function () {
        debugger;
        $scope.authError = null;
        var data = { UserName: $scope.user.email, Password: $scope.user.password };

        $http.post('http://localhost:54681/api/AccessToken/Generate', data)
        .then(function (response) {
            debugger;
            //if (!response.data.user) {
            //    $scope.authError = 'Email or Password not right';
            //} else {
            //    $state.go('app.dashboard-v1');
            //}
        }, function (x) {
            debugger;
            console.log(x);
            //$scope.authError = 'Server Error';
        });
    };
}]);

2 - Asp.net Web Api controller on //localhost:54681/

[RoutePrefix("api/AccessToken")]
public class AccessTokenController : BaseApiController
{
    #region Properties And Variable Declaration

    private IAccessTokenCurator accessTokenCurator;

    #endregion Properties And Variable Declaration

    #region Constructor

    public AccessTokenController(IAccessTokenCurator accessTokenCurator)
    {
        this.accessTokenCurator = accessTokenCurator;
    }

    #endregion Constructor

    #region Access Token Operation

    [HttpPost]
    [Route("Generate")]
    public async Task<HttpResponseMessage> Generate(UserLogOn userLogOnModel)
    {
        ServiceResponse<string> serviceResponse = null;

        serviceResponse = new ServiceResponse<string>(await accessTokenCurator.Generate(userLogOnModel));

        return Request.CreateResponse<ServiceResponse<string>>(serviceResponse);
    }

    #endregion Access Token Operation
}

3 - UserLogOn class on //localhost:54681/

public class UserLogOn
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

4 - Web.config changes on //localhost:54681/

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    </handlers>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="content-type" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Max-Age" value="1000" />
        <add name="Access-Control-Allow-Request-Method" value="GET, POST, PUT, DELETE, OPTIONS" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Let me know where I am making mistake(s).

Dinesh
  • 255
  • 1
  • 2
  • 14
  • When i do this $http.get('http://localhost:54681/api/AccessToken/Validate?token=xx4QQGImMLR9hG6Hbry%2FBvENEejJP5SOrAbtvJCgw2r%2F%2Fj0O01OuWgIbozkxKP0idF2Capx7Xtg%3D') .then(function (response) { debugger; }, function (x) { console.log(x); debugger; }); Then it works. i.e. For Http Get request it is working but for Http Post it is not working. – Dinesh Oct 20 '16 at 13:05
  • One more thing $http.post works when i pass serilized data with form-urlencoded content-type header. But I am unable to pass json data using http.post method – Dinesh Oct 20 '16 at 13:10
  • the it seems it is how your server accepts the requests. Why not just specify that the data is form data? – joncodo Oct 20 '16 at 13:17
  • Request Header Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8,es;q=0.6 Connection:keep-alive Content-Length:27 Content-Type:application/x-www-form-urlencoded DNT:1 Host:localhost:54681 Origin:http://localhost:62319 Referer:http://localhost:62319/src/index.html User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 – Dinesh Oct 20 '16 at 13:20
  • Response Header Request URL:http://localhost:54681/api/AccessToken/Generate Request Method:POST Status Code:200 OK Remote Address:[::1]:54681 when i pass serilized data with form-urlencoded content-type header then it works – Dinesh Oct 20 '16 at 13:21
  • what is response.body – joncodo Oct 20 '16 at 13:23
  • Request URL:http://localhost:54681/api/AccessToken/Generate Request Method:OPTIONS Status Code:404 Not Found Remote Address:[::1]:54681 Cache-Control:private Content-Length:5014 Content-Type:text/html; charset=utf-8 Date:Thu, 20 Oct 2016 13:33:58 GMT Server:Microsoft-IIS/8.0 X-Powered-By:ASP.NET X-SourceFiles:=?UTF-8?B?RDpcRGluZXNoXFNvdXJjZUNvZGVcSGVhbHRoIE1vbml0b3JcQmFzZVdlYkFwaVRlbXBsYXRlXFNlcnZpY2VzXEJhc2UuU2VydmljZXMuQXBpXGFwaVxBY2Nlc3NUb2tlblxHZW5lcmF0ZQ==?= – Dinesh Oct 20 '16 at 13:37
  • @joncodo It is making option request instead of post request. ---- Then it throws error : XMLHttpRequest cannot load http://localhost:54681/api/AccessToken/Generate. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49241' is therefore not allowed access. The response had HTTP status code 404. angularDOM.html:27 Object {data: null, status: -1, config: Object, statusText: ""} – Dinesh Oct 20 '16 at 13:38
  • So I'm guessing it makes the options request first to see if it can post. Then makes the post request. but the options one is blocked by cors. You need all routes true and your origin set on that request – joncodo Oct 20 '16 at 13:45
  • @joncodo Yes!!! What setting has to be done on Web API side to allow option request so that it is not blocked by cors. ----------Can you explain in detail "You need all routes true and your origin set on that request " – Dinesh Oct 20 '16 at 14:07
  • $httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = 'origin, content-type, accept'; $httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*'; $httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET,POST,PUT,HEAD,DELETE,OPTIONS';*/ – joncodo Oct 20 '16 at 15:23

1 Answers1

1

I'm guessing that you are getting blocked by CORS How does Access-Control-Allow-Origin header work?

Make sure to set:

'Access-Control-Allow-Headers' = 'origin, content-type, accept';
'Access-Control-Allow-Origin' = '*';
'Access-Control-Allow-Methods' = 'GET,POST,PUT,HEAD,DELETE,OPTIONS';

Step 1: Make sure your route actually works

You can try a tool called postman.

This will show you if your url route to /localhost:62319/ is working.

Step 2: Test $http.post

$http.post('http://localhost:54681/api/AccessToken/Generate?data=' + 'foo')

Does this method work for you?

Step 3: Check the network tab and show the results

Open up the chrome developer tools and find the network tab. Click on the request and then the response. Is it coming back as 404?

Community
  • 1
  • 1
joncodo
  • 2,298
  • 6
  • 38
  • 74
  • I use swagger for that thing and it works, actually when i do jquery ajax post then too it works but not for angular $htpp.post() method – Dinesh Oct 20 '16 at 13:13
  • try http.get('http://www.google.com') to make sure http is working for you in this page. Any console errors? – joncodo Oct 20 '16 at 13:14
  • are you getting into the success or error function of the .post? – joncodo Oct 20 '16 at 13:15