AngularJs $http.post() does not send data

前端 未结 30 1805
我在风中等你
我在风中等你 2020-11-22 02:51

Could anyone tell me why the following statement does not send the post data to the designated url? The url is called but on the server when I print $_POST - I get an empty

相关标签:
30条回答
  • 2020-11-22 03:19

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

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

    About the data format:

    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.

    Try to use this variation

    function sendData($scope) {
        $http({
            url: 'request-url',
            method: "POST",
            data: { 'message' : message }
        })
        .then(function(response) {
                // success
        }, 
        function(response) { // optional
                // failed
        });
    }
    
    0 讨论(0)
  • 2020-11-22 03:19

    Add this in your js file:

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

    and add this to your server file:

    $params = json_decode(file_get_contents('php://input'), true);
    

    That should work.

    0 讨论(0)
  • 2020-11-22 03:20

    I solved this by below codes:

    Client Side (Js):

         $http({
                    url: me.serverPath,
                    method: 'POST',
                    data: data,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                }).
                    success(function (serverData) {
                        console.log("ServerData:", serverData);
        ......
    

    notice that data is an object.

    On the server (ASP.NET MVC):

    [AllowCrossSiteJson]
            public string Api()
            {
                var data = JsonConvert.DeserializeObject<AgentRequest>(Request.Form[0]);
                if (data == null) return "Null Request";
                var bl = Page.Bl = new Core(this);
    
                return data.methodName;
            }
    

    and 'AllowCrossSiteJsonAttribute' is needed for cross domain requests:

    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
                base.OnActionExecuting(filterContext);
            }
        }
    

    Hope this was useful.

    0 讨论(0)
  • 2020-11-22 03:21

    I had the same problem with AngularJS and Node.js + Express 4 + Router

    Router expects the data from post's request in body. This body was always empty if i followed the example from Angular Docs

    Notation 1

    $http.post('/someUrl', {msg:'hello word!'})
    

    But if i used it in the data

    Notation 2

    $http({
           withCredentials: false,
           method: 'post',
           url: yourUrl,
           headers: {'Content-Type': 'application/x-www-form-urlencoded'},
           data: postData
     });
    

    Edit 1:

    Otherwise node.js router will expect the data in req.body if used notation 1:

    req.body.msg
    

    Which also sends the information as JSON payload. This is better in some cases where you have arrays in your json and x-www-form-urlencoded will give some problems.

    it worked. Hope it helps.

    0 讨论(0)
  • 2020-11-22 03:22

    To send data via Post methode with $http of angularjs you need to change

    data: "message=" + message, with data: $.param({message:message})

    0 讨论(0)
  • 2020-11-22 03:22

    Angular

      var payload = $.param({ jobId: 2 });
    
                    this.$http({
                        method: 'POST',
                        url: 'web/api/ResourceAction/processfile',
                        data: payload,
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                    });
    

    WebAPI 2

    public class AcceptJobParams
            {
                public int jobId { get; set; }
            }
    
            public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
            {
                // do something with fileName parameter
    
                return Ok();
            }
    
    0 讨论(0)
提交回复
热议问题