AngularJs $http.post() does not send data

前端 未结 30 1811
我在风中等你
我在风中等你 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: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(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.

提交回复
热议问题