Rectangle 27 6

web.config
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
PUT
DELETE
CORS

I've already tried but no use :(

What's your definition for ScenarioRequestParams? My guess is that you're construction your post request in the wrong manner.

Are you truly using WeB API, because you have posted code from an ASMX web service.

param is "ScenarioId": 10, it is not issue with request param. I've tested POST scenario in fiddler it is working good. Some how it is not working from application.

Are you configuring CORS via configuration as well? If not you should remove that. Other than that your Web API looks like. The problem should be in your firewall.

asp.net - AngularJS $http.POST method 405 error - Stack Overflow

asp.net angularjs asp.net-web-api cors
Rectangle 27 6

web.config
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
PUT
DELETE
CORS

I've already tried but no use :(

What's your definition for ScenarioRequestParams? My guess is that you're construction your post request in the wrong manner.

Are you truly using WeB API, because you have posted code from an ASMX web service.

param is "ScenarioId": 10, it is not issue with request param. I've tested POST scenario in fiddler it is working good. Some how it is not working from application.

Are you configuring CORS via configuration as well? If not you should remove that. Other than that your Web API looks like. The problem should be in your firewall.

asp.net - AngularJS $http.POST method 405 error - Stack Overflow

asp.net angularjs asp.net-web-api cors
Rectangle 27 1

$http({
    url: "",
    method: "POST",
    data: $.param({
        data1: ""       
    }),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

I was also facing this issue. Was getting 405 and OPTIONS was made. I came across a blog and found that the way angular encodes param is not understood by web server properly. So, jQuery is required to encode POST data

asp.net - AngularJS $http.POST method 405 error - Stack Overflow

asp.net angularjs asp.net-web-api cors
Rectangle 27 1

$http({
    url: "",
    method: "POST",
    data: $.param({
        data1: ""       
    }),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

I was also facing this issue. Was getting 405 and OPTIONS was made. I came across a blog and found that the way angular encodes param is not understood by web server properly. So, jQuery is required to encode POST data

asp.net - AngularJS $http.POST method 405 error - Stack Overflow

asp.net angularjs asp.net-web-api cors
Rectangle 27 14

After hours of struggling, this is final solution that helped me (tested from fiddler):

  • Choose "Add module mapping" option on the right side of the panel
  • Click on "Request restrictions" and go to Verbs tab

End voila, fiddler no longer answers with 405 but with happy 200.

Buhtla, if this is the answer that solved the problem for you, mark it as such with the green checkmark. This is allowed (and encouraged) on SO.

Helped me after searching all morning for a fix - thanks

How did you find out about this @buhtla? It worked for me: big thanks! But I think it would also be helpful to post the URL from where you got this information and, please, mark as answer because it will be easier for others to find the solution.

I'm very glad I helped you guys! It passed quite some time after I had this problem, but I remember I found out this solution on my own. Maybe there are some pages that have this same resolution of the problem described, but I'm not aware of them.

Worked for me as well, you are great!

c# - IIS 7.5, Web Service and HTTP 405 error - Stack Overflow

c# wcf iis http-post
Rectangle 27 321

I had the same problem using asp.net MVC and found the solution here

There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) dont appear to be swappable with the jQuery equivalents (jQuery.post(), etc.)

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJSs transmission natively ... By default, jQuery transmits data using

Content-Type: x-www-form-urlencoded

and the familiar foo=bar&baz=moe serialization.

Content-Type: application/json
{ "foo": "bar", "baz": "moe" }

Works like a charm.

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
bower install angular-post-fix --save-dev

so is there a way to change php's transmits data method. Because that is the issue I am having currently.

This code works great on the most part, but I've had issues with it when submitting a hierarchy of empty objects or even flat empty values. For example, { a: 1, b: { c: { d: { } } }, e: undefined, f: null, g: 2 } will not be encoded properly, and PHP will get it as [ "a" => "1", "g" => "2" ]. The entire structure under "b", as well as "e" and "f", including the keys themselves - would be lost. I posted alternative code below, with which the above structure gets decoded as: [ "a" => "1", "b" => [ "c" => [ "d" => "" ] ], "e" => "", "f" => "", "g" => "2" ].

Amazing. I faced a lot of problem but this solved it. :)

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 321

I had the same problem using asp.net MVC and found the solution here

There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) dont appear to be swappable with the jQuery equivalents (jQuery.post(), etc.)

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJSs transmission natively ... By default, jQuery transmits data using

Content-Type: x-www-form-urlencoded

and the familiar foo=bar&baz=moe serialization.

Content-Type: application/json
{ "foo": "bar", "baz": "moe" }

Works like a charm.

// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */ 
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});
bower install angular-post-fix --save-dev

so is there a way to change php's transmits data method. Because that is the issue I am having currently.

This code works great on the most part, but I've had issues with it when submitting a hierarchy of empty objects or even flat empty values. For example, { a: 1, b: { c: { d: { } } }, e: undefined, f: null, g: 2 } will not be encoded properly, and PHP will get it as [ "a" => "1", "g" => "2" ]. The entire structure under "b", as well as "e" and "f", including the keys themselves - would be lost. I posted alternative code below, with which the above structure gets decoded as: [ "a" => "1", "b" => [ "c" => [ "d" => "" ] ], "e" => "", "f" => "", "g" => "2" ].

Amazing. I faced a lot of problem but this solved it. :)

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 6

The listed answer didn't work for me, but I was able to fix the problem by running

c# - IIS 7.5, Web Service and HTTP 405 error - Stack Overflow

c# wcf iis http-post
Rectangle 27 31

myobject = {'one':'1','two':'2','three':'3'}

Object.toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
        p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
};

$http({
    method: 'POST',
    url: url,
    data: Object.toparams(myobject),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

the function ObjecttoParams works like charm ! Thanks a lot.

Simplest solution in my opinion!

Worked like a charm.. +1

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 31

myobject = {'one':'1','two':'2','three':'3'}

Object.toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
        p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
};

$http({
    method: 'POST',
    url: url,
    data: Object.toparams(myobject),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

the function ObjecttoParams works like charm ! Thanks a lot.

Simplest solution in my opinion!

Worked like a charm.. +1

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 2

Goto IIS Manager -> Select Web Site -> Handler Mapping -> Select the handler -> right-click and select edit -> Request restrictions -> verbs tab

Depending on your extension, it could be a different handler.

Yes, but for what handler? I have no specific handler for wsdl extension.

I am implementing this with WCF, so this is actually .svc extension. I have already checked, and for svc extension all verbs are allowed. Still I get same error...

I have finally found a solution. I posted it as an answer. Thanks anyway.

c# - IIS 7.5, Web Service and HTTP 405 error - Stack Overflow

c# wcf iis http-post
Rectangle 27 106

I needed to add true to force it to an array when overwriting the $_POST array with it. json_decode(file_get_contents('php://input'), true);

hacky, should not be used as a universal solution

@Zalaboza, I would agree that it is tough to have any solution considered 'universal' but I don't agree that it is 'hacky'--- php.net states: "file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance." Granted we're not reading a file in this situation but we are nonetheless reading posted json data. It would be great if you could contribute a new answer or provide new information to help readers (including myself) make a better decision about this.

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 105

I needed to add true to force it to an array when overwriting the $_POST array with it. json_decode(file_get_contents('php://input'), true);

hacky, should not be used as a universal solution

@Zalaboza, I would agree that it is tough to have any solution considered 'universal' but I don't agree that it is 'hacky'--- php.net states: "file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance." Granted we're not reading a file in this situation but we are nonetheless reading posted json data. It would be great if you could contribute a new answer or provide new information to help readers (including myself) make a better decision about this.

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 70

You can set the default "Content-Type" like this:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
data

The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.

function sendData($scope) {
    $http({
        url: 'request-url',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

It doesn't seem to work. I've just tried the variation with the data as string and : headers: {'Content-Type': 'application/x-www-form-urlencoded'} - and that seem to work, but is there a better way of doing it?

Set default content type as described above and for data don't use js object. Use string like this: 'message='+message Works for me

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 70

You can set the default "Content-Type" like this:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
data

The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.

function sendData($scope) {
    $http({
        url: 'request-url',
        method: "POST",
        data: { 'message' : message }
    })
    .then(function(response) {
            // success
    }, 
    function(response) { // optional
            // failed
    });
}

It doesn't seem to work. I've just tried the variation with the data as string and : headers: {'Content-Type': 'application/x-www-form-urlencoded'} - and that seem to work, but is there a better way of doing it?

Set default content type as described above and for data don't use js object. Use string like this: 'message='+message Works for me

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 9

Error #1 - The iteration update

There are two things that aren't quite correct with your Newton-Raphson technique... but certainly fixable! After we fix this, there is no need for the VPA error that you're speaking of.

The first one is the iteration itself. Recall the definition of the Newton-Raphson technique:

For the next iteration, you use the previous iteration's value. What you're doing is using the loop counter and substituting this into your f(x), which is not correct. It must be the previous iteration's value.

If you take a look at how you're coding your function, you define your function symbolically, yet you are trying to substitute numeric values into your function. This unfortunately doesn't fly with MATLAB. If you actually want to substitute values in, you have to use subs. This will substitute an actual value for you as a function of x or whichever independent variable your function is using. Once you do this, your value is still a sym type. You need to cast this as double in order to be able to use this numerically.

Also for efficiency, there is no need to make y an array. Just make this a single value that updates itself at each iteration. With all of this being said, your code is updated to look like this. Mind you, I took the derivative of the function before the loop to decrease the amount of computation you need to take. I also split up the numerator and denominator terms for the Newton-Raphson iterations to make things clear, and to make this more palatable for subs. Without further ado:

function r = mynewton(f,a,n)
syms x;
z = f(x);
diffZ = diff(z); %// Edit - Include derivative
y = a; %// Initial root

for idx = 1 : n    
    numZ = subs(z,x,y); %// Numerator - Substitute f(x) for f(y)
    denZ = subs(diffZ,x,y); %// Denominator - Substitute for f'(x) for f'(y)
    y = y - double(numZ)/double(denZ); %// Update - Cast to double to get the numerical value
end
r = y; %// Send to output
end

Take note that I replaced i with idx in the loop. The reason why is because it is actually not recommended to use i or j as loop indices as these letters are reserved to represent complex numbers. If you take a look at this post by Shai, you'll see that it's actually slower to use these variables as loop indices: Using i and j as variables in Matlab

In any case, to test this out, suppose our function was y = sin(x), and my initial root was x0 = 2, with 5 iterations, we do:

f = @(x) sin(x);
r = mynewton(f, 2, 5)

r =

3.1416

This agrees with our knowledge of sin(x), as the intercepts of sin(x) are located at integer multiples of pi. x0 = 2 is located near pi so this does work as we expected.

Your original code had the values of the root stored at each iteration in y. If you really want to do that, you'll have to modify your code so that it looks something like this. Bear in mind that I pre-allocated y to make things more efficient:

function r = mynewton(f,a,n)
syms x;
z = f(x);
diffZ = diff(z);
y = zeros(1,n+1); %// Pre-allocate output array 
y(1) = a; %// First entry is the initial root

for idx = 1 : n    
    numZ = subs(z,x,y(idx)); %// Remember to use PREVIOUS guess for next guess
    denZ = subs(diffZ,x,y(idx));
    y(idx+1) = y(idx) - double(numZ)/double(denZ); %// Place next guess in right spot  
end
r = y; %// Send to output
end

By running this code using the exact same parameters as above, we get:

f = @(x) sin(x);
r = mynewton(f, 2, 5)

r =

    2.0000    4.1850    2.4679    3.2662    3.1409    3.1416

Each value in r tells you the guess of the root at that particular iteration. The first element of the array is the initial guess (of course). The next values are the guesses at each iteration of the Newton-Raphson root. Take note that the last element of the array is our final iteration, which is roughly equal to pi.

Oh yeah so that's what OP means by diff(z).... Another amazing work by rayryeng! By the way, would you consider speeding up this function by converting z and diff(z) before the loop? mathworks.com/help/symbolic/

@Yvon - Of course. Didn't consider that. That'll definitely speed things up!... and thanks for the compliments :)

@rayryeng I would rather use a tolerance, while ( dy>tol ) & ( idx<n ). The point is that there is nothing that say that the number of iterations requested is enough, nor anything confirming that the algorithm would actually converge. Otherwise, good job! Everyting is very nice and clean.

Newton-Raphson Method in Matlab - Stack Overflow

matlab numerical-methods newtons-method
Rectangle 27 47

I have had a similar issue, and I wonder if this can be useful as well: https://stackoverflow.com/a/11443066

var xsrf = $.param({fkey: "key"});
$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

It looks like the headers was the only change we needed. Thank you!

Thanks, that did it for me :) The problem was the encoding of the POST data.

Thanks, this worked (and is nicest solution of this page!)

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 47

I have had a similar issue, and I wonder if this can be useful as well: https://stackoverflow.com/a/11443066

var xsrf = $.param({fkey: "key"});
$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

It looks like the headers was the only change we needed. Thank you!

Thanks, that did it for me :) The problem was the encoding of the POST data.

Thanks, this worked (and is nicest solution of this page!)

AngularJs $http.post() does not send data - Stack Overflow

angularjs post angular-http
Rectangle 27 19

Your data should be a key/val pair, try:

$http.post('javaServerlet', {course: $scope.getCourse})

And that variable will get to the server under the parameter course

Perfect! Thanks a lot for ur quick response.

If there are multiple parameters, are they just comma-separated?

How to pass parameter in Angularjs $http.post - Stack Overflow

angularjs
Rectangle 27 26

1 - Don't mock the service and use $httpBackend to setup expectations ...

As someone had mentioned in a deleted answer, success and error are syntactic sugar added by $http so they aren't there when you create your own promise. You have two options:

The idea is to let your myService act like it normally would without knowing it's being tested. $httpBackend will let you set up expectations and responses, and flush them so you can complete your tests synchronously. $http won't be any wiser and the promise it returns will look and function like a real one. This option is good if you have simple tests with few HTTP expectations.

If the thing you're testing has complicated dependencies and all the set-up is a headache, you may still want to mock the services and the calls themselves as you have attempted. The difference is that you'll want to fully mock promise. The downside of this can be creating all the possible mock promises, however you could make that easier by creating your own function for creating these objects.

The reason this works is because we pretend that it resolves by invoking the handlers provided by success, error, or then immediately, causing it to complete synchronously.

'use strict';

describe('SimpleControllerTests', function () {

    var scope;
    var expectedResponse = { name: 'this is a mocked response' };
    var $controller, _mockMyService, _mockPromise = null;

    beforeEach(module('myApp'));

    beforeEach(inject(function(_$rootScope_, _$controller_){ 
        $controller = _$controller_;
        scope = _$rootScope_;

        _mockMyService = {
            get: function() {
               return _mockPromise;
            }
        };
    }));

    describe('should load data successfully', function() {

        beforeEach(function() {

          _mockPromise = {
             then: function(successFn) {
               successFn(expectedResponse);
             },
             success: function(fn) {
               fn(expectedResponse);
             }
          };

           $controller('SimpleController', { $scope: scope, myService: _mockMyService });
        });

        it('using loadData()', function() {
          scope.loadData();
          expect(scope.data).toEqual(expectedResponse);
        });

        it('using loadData2()', function () {
          scope.loadData2();
          expect(scope.data).toEqual(expectedResponse);
        });
    });

    describe('should fail to load data', function() {
        beforeEach(function() {
          _mockPromise = {
            then: function(successFn, errorFn) {
              errorFn();
            },
            error: function(fn) {
              fn();
            }
          };

          $controller('SimpleController', { $scope: scope, myService: _mockMyService });
        });

        it('using loadData()', function() {
          scope.loadData();
          expect(scope.error).toEqual("ERROR");
        });

        it('using loadData2()', function () {
          scope.loadData2();
          expect(scope.error).toEqual("ERROR");
        });
    });           
});

I rarely go for option 2, even in big applications.

For what it's worth, your loadData and loadData2 http handlers have an error. They reference response.data but the handlers will be called with the parsed response data directly, not the response object (so it should be data instead of response.data).

Thanks for the answer, how would I test the error condition though? I'm starting to think using success and error explicitly outside the controller is really a bad idea. I'm thinking the controller code should be then(function(..success code here..), function(..error code here...) . Then I can simulate success \ error from the test using resolve() and reject() on the promise..

That's why option #2 sucks. If you want an error condition, move the $httpBackend setup and controller init into the body of the fact, or put it in it's own describe block that has the varied beforeEach. I'll update my example with success and fail.

OK, updated. Sorry if there are typos or small errors, I had to rush because a meeting just got called :p

Thanks a lot for the detailed answer, this really got me thinking and I've decided that success and error have no place in my controller. Points to you though, you provided a perfectly workable solution. That dependency on the actual service implementation is something I'd rather avoid. Maybe I'm being too idealistic :)

At the end of the day, whatever you're comfortable with. But the way I've always looked at it, when dealing with external data, I'm testing a controller I want to make sure it's calling the service(s) to load or submit the data using the correct parameters when it's supposed to, and it's doing the right thing with the potential responses. Doing so by controlling it in one simple spot, $httpBackend, is the closest to the real thing while remaining practical and easy to implement in my tests. Again, it depends on what the service does, but truly and necessarily complicated services are rare.

javascript - Test a controller with success() and error () - Stack Ove...

javascript angularjs unit-testing jasmine