草庐IT

javascript - AngularJS $http.post 与正文

coder 2024-07-27 原文

我有一个使用 CordovaAngularJS 的应用程序。

使用 Angular,我向我的后端应用程序 (Spring REST) 发送一个值。我为此使用的方法是 $http.post


问题

当我尝试将数据发送到我的服务器时,Spring 不会在我的实体中设置值。因此,我无法保存我的新数据。


Angular 代码

我的 AngularJS 代码如下:

httpService.createInBackend = function (url, data, callback, errorCallback) {
    http.post(url, data)
           .then(function (success) {
              callback(success);
           }, function (error) {
              errorCallback(error.data);
           });
};

我使用以下参数:

网址:http://<location>:<port>/<application>/<web_socket_url>

数据:

data: {
        {
        "incidentTypeId": 5,
        "priorityId": 1,
        "creationDate": 1449676871234,
        "userId": 1,
        "latitude": <some valid location>,
        "longitude": <some valid location>
        }
    },
    timeout: 4000
}

我使用“data”而不是“params”,因为我想通过正文发送数据。我让它与 PUT 函数一起使用,它与这个函数没有太大区别。


我的 REST Controller

 @RequestMapping(value = "/employee/new", method = RequestMethod.POST)
    public NewEmployee createIncident(@RequestBody NewEmployee employee) {

    return employee;
}

我的新员工模型

private int employeeId;

private int priorityId;

private String information;

private Date creationDate;

private int userId;

private float longitude;

private float latitude;

Angular 结果

使用控制台时,我从该方法得到以下结果:

我发送:

{
     "employeeId":5,
     "priorityId":1,
     "creationDate":1449677250732,
     "userId":1,
     "information": "hello world!",
     "latitude":<some valid location>,
     "longitude":<some valid location>
}

我收到:

{  
     employeeId: 0
     priorityId: 0
     creationDate: null
     userId: 0
     information: null
     latitude: 0
     longitude: 0   
}

postman

我用 PostMan(Google chrome 插件)尝试了同样的事情,我的代码就是这样工作的。因此,我确实认为这是我的 AngularJS 代码的问题。


我试过了

我尝试使用以下 AngularJS 调用:

$http({
    method: 'POST',
    url: url,
    data: data,
    timeout: 4000
}).then(function (success) {
    callback(success);
}, function (error) {
    errorCallback(error);
});

但这并没有改变结果。仍然只有空值。


有人知道我做错了什么吗?

最佳答案

您是否尝试过不使用 $http 的简写版本? 我认为如果您使用类似的代码,您的代码将有效

$http({
  method: 'POST',
  url: url,
  data: JSON.stringify(data)
})
.then(function (success) {
  callback(success);
}, function (error) {
  errorCallback(error.data);
});

在哪里

data = {
     "employeeId":5,
     "priorityId":1,
     "creationDate":1449677250732,
     "userId":1,
     "information": "hello world!",
     "latitude":<some valid location>,
     "longitude":<some valid location>
}

Further reading...

关于javascript - AngularJS $http.post 与正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34183894/

有关javascript - AngularJS $http.post 与正文的更多相关文章

  1. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  2. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  3. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  4. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  5. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  6. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  7. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  8. ruby-on-rails - Rails - 从命名路由中提取 HTTP 动词 - 2

    Rails中有没有一种方法可以提取与路由关联的HTTP动词?例如,给定这样的路线:将“users”匹配到:“users#show”,通过:[:get,:post]我能实现这样的目标吗?users_path.respond_to?(:get)(显然#respond_to不是正确的方法)我最接近的是通过执行以下操作,但它似乎并不令人满意。Rails.application.routes.routes.named_routes["users"].constraints[:request_method]#=>/^GET$/对于上下文,我有一个设置cookie然后执行redirect_to:ba

  9. ruby-on-rails - Heroku 吃掉了我的自定义 HTTP header - 2

    我正在使用Heroku(heroku.com)来部署我的Rails应用程序,并且正在构建一个iPhone客户端来与之交互。我的目的是将手机的唯一设备标识符作为HTTPheader传递给应用程序以进行身份​​验证。当我在本地测试时,我的header通过得很好,但在Heroku上它似乎去掉了我的自定义header。我用ruby​​脚本验证:url=URI.parse('http://#{myapp}.heroku.com/')#url=URI.parse('http://localhost:3000/')req=Net::HTTP::Post.new(url.path)#boguspara

  10. ruby-on-rails - 使用 HTTP.get_response 检索 Facebook 访问 token 时出现 Rails EOF 错误 - 2

    我试图在我的网站上实现使用Facebook登录功能,但在尝试从Facebook取回访问token时遇到障碍。这是我的代码:ifparams[:error_reason]=="user_denied"thenflash[:error]="TologinwithFacebook,youmustclick'Allow'toletthesiteaccessyourinformation"redirect_to:loginelsifparams[:code]thentoken_uri=URI.parse("https://graph.facebook.com/oauth/access_token

随机推荐