简体   繁体   English

AngularJS PUT与Symfony2 PUT方法 更新不起作用

[英]AngularJS PUT vs Symfony2 PUT method. Update doesn't work

I'm building app in symfony2.4 and angularjs. 我正在symfony2.4和angularjs中构建应用程序。 In angular I've created resource: 在角度我创建了资源:

app.factory('Tasks', ['$resource', function($resource) {
    return $resource( 'api/tasks/:taskid', null,
         {
            'update': { method:'PUT' }
        });
}]);

and when I'm trying to update like this: Tasks.update({ taskid : task.id },task); 当我尝试像这样更新时: Tasks.update({ taskid : task.id },task); I'm getting this error: 我收到此错误:

{"code":400,"message":"Validation Failed","errors":{"errors":["The CSRF token is invalid. Please try to resubmit the form."],"children":{"timeStart":{"children":{"date":[],"time":[]}},"timeStop":{"children":{"date":[],"time":[]}},"project":[],"descriptionTask":[],"isCompleted":[],"isVisible":[]}}}

When I build form in symfony and then update any task - it works. 当我在symfony中构建表单然后更新任何任务时-它可以工作。 But I noticed that AngularJS doesn't send any data via POST . 但是我注意到AngularJS不会通过POST发送任何数据 It sends via JSON(? or just sends this object I'm giving ) and I think this is the problem. 它通过JSON发送(?或只是发送我给的对象),我认为这是问题所在。 How can I repair it? 我该如何修理?

You need to add the _token in your form ie 您需要在表单中添加_token ,即

 {{ form_row(form._token) }} 

As of now your form is missing with the csrf token field,if you use the twig form functions to render your form like form(form) this will automatically renders the csrf token field for you but your code show your are rendering your form with raw html for form like <form></form> then you have to manually render the field 到目前为止,您的表单缺少csrf令牌字段,如果您使用细枝表单函数来呈现form(form)form(form)这将自动为您呈现csrf令牌字段,但是您的代码显示您正在使用raw呈现表单像<form></form>这样的<form></form> html,那么您必须手动呈现该字段

or simply add {{ form_rest(form) }} before closing tag of form 或仅在关闭表单标记之前添加{{ form_rest(form) }}

According to docs 根据文档

This renders all fields that have not yet been rendered for the given form. 这将呈现给定表单尚未呈现的所有字段。 It's a good idea to always have this somewhere inside your form as it'll render hidden fields for you and make any fields you forgot to render more obvious (since it'll render the field for you). 始终将其保留在表单内是一个好主意,因为它将为您呈现隐藏的字段,并使您忘记呈现的所有字段变得更加明显(因为它将为您呈现该字段)。

form_rest(view, variables) form_rest(视图,变量)

Answer from @M Khalid Junaid in The CSRF token is invalid. 来自@M Khalid Junaid 的CSRF令牌答案无效。 Please try to resubmit the form 请尝试重新提交表格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM