【问题标题】:Angularjs post does not send the data on serverAngularjs 帖子不会在服务器上发送数据
【发布时间】:2016-04-20 15:52:52
【问题描述】:

我正在尝试将数据发布到服务器,但在服务器端,我的模型为空。

数据是

{"email":"adas","password":"sds","grant_type":"password","client_id":"WebApp"}

 return $http.post(url, data,{headers: {'Content-Type': 'application/json'} })
            .then(function (result) {
                success(result);
            }, function (error) {
                debugger;
               //some code
            });

但是当我使用简单的 ajax 请求发送它时,我会在服务器端获取我的数据。

 var logininfo = { "email": "weee", "password": "password", "client_id": "IosApp", "grant_type": "password" };
        $.ajax({
            url: "http://localhost:53646/Login",                 
            type: "POST",
            data: logininfo,
            success: function (data) {
                debugger;
            }, error: function (daTA) {
                debugger;
            }
        }); 

还有一个问题,因为我必须向服务器发送一个自定义标头,所以当我在 ajax 请求中设置该标头时,我的数据再次在服务器端为空。

var logininfo = { "email": "weee", "password": "password", "client_id": "IosApp", "grant_type": "password" };
        $.ajax({
            url: "http://localhost:53646/Login",
            headers: { 'ResourceAuthorization': 'Basic Qn12bGV34jEyMzQ1' },          
            type: "POST",
            data: logininfo,
            success: function (data) {
                debugger;
            }, error: function (daTA) {
                debugger;
            }
        });

这就是我尝试获取数据的方式

public void Configuration(IAppBuilder app)
        {
            app.Use(async (ctx, n) =>
            {
                if (ctx.Request.Path == new PathString("/Login"))
                {
                    var memstr = new StreamReader(ctx.Request.Body).ReadToEndAsync().Result; 
                    var loginmodel = JsonConvert.DeserializeObject<LoginModel>(memstr);   
                   //some code here                 
                }
                await n.Invoke();
            });
            ConfigureAuth(app);
        }

【问题讨论】:

  • 你在 Angular 的 $http 中输入:'POST'。它应该是方法:'POST'
  • @MegaRacer $http.post 将在内部执行此操作
  • 谢谢@PankajParkar
  • @PankajParkar :我解决了数据问题。但是现在如何在所有请求中发送我的自定义标头。 ?
  • 您应该使用 httpIntrerceptor,它会在发送前在每个请求中添加标头

标签: c# angularjs ajax asp.net-mvc asp.net-web-api


【解决方案1】:

在您的http 请求中使用角度承诺总是更好。它保证了结果。处理错误也很容易和有用。

var userObject = = {
    email: "user@gmail.com",
    UserName: 'user123'
}

function LoginUser (userObj) {
  return $http.post('http://localhost:53646/Login', userObj,
       headers : {'ResourceAuthorization': 'Basic Qn12bGV34jEyMzQ1'}
  ).then(function (response) {
     console.log(response.data);
     return response.data;
  }, function (error) {
     console.log(error);
  });
};

最好将 http 调用创建为服务或函数,以便我们可以重用它。

运行这个 http 调用

只需将函数调用为

LoginUser(userObject);

【讨论】:

  • 不要使用 $q 来返回承诺。因为你已经有 $http.post 返回的承诺 +1 为 ResourceAuthorization 包含在标题中
  • 但我认为 $http.post 仅返回已解析的数据,而不是承诺
  • 请阅读角度文档 $http 的工作原理。尽管我在您的回答中进行了编辑。谢谢:-)
【解决方案2】:

试试这个方法..这在我的项目中有效。

var userData = {
            UserId: 1,
            UserName: 'Karan'
            }
var result = $http({
            url: "http://your_URL",
            dataType: 'json',
            method: 'POST',
            data: userData,
            headers: {
                "Content-Type": "application/json"
            }
        })
        result.success(function (data, status, headers, config) {
            //success
        });
        result.error(function (data, status, headers, config) {
            //Error
        });

【讨论】:

  • 你在webapi控制器中写过[HttpPost]吗?
  • 是的。当我通过 ajax 发送它时,我正在获取数据'
【解决方案3】:

s这可能很棘手,我总是必须检查网络事务以确定它是否真的是一个 POST,这里是我的代码示例:

function postMEthod(ID) {
      var postURL = "your_url";

      var request = $http({
        method: 'POST',
        headers: {"Content-Type": 'text/plain; charset=UTF-8'},
        url: postURL,
        data: {
          dataParam: "value1",
          dataParam2: "value2"
        }
      });
      return ( request.then(handleSuccess, handleError) );
    }

希望对你有帮助。

【讨论】:

    【解决方案4】:

    看到它的工作 -

    self.data = { "email": "adas", "password": "sds", "grant_type": "password", "client_id": "WebApp" };
    self.getData = $http.post('../api/Controller/PostItem', JSON.stringify(self.data))
    .then(function success(a, b) {
        //
    }, function error(a, b) {
        //
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多