In Backbone.js, how can I add an attribute to the parameters every time there is a POST request?

model.save(), collection.create() 

When I call these two things, the client sends a POST request with the model data to my server. Awesome. But what if I want to add an attribute to it?

I want to add "csrf_token: 12345" to the data before sending a POST request to my server.

How can i add this? automatically? I want this to happen with all of my ideas.

+4
source share
2 answers

A better option would be to use the jQuery ajaxSetup method to add csrf_token for each request.

It is as simple as adding this line of code (outside your baseline code):

 $.ajaxSetup({ data: { 'csrf_token' : '12345' }}); 

Since Backbone uses jQuery for all its ajax communication, csrf_token will be included in every ajax request.

See the blog post for more details.

0
source

Perhaps the following will do the trick:

 CSRFAwareModel = Backbone.Model.extend({ defaults: { 'csrf_token': getToken() } }); MyModel = CSRFAwareModel.extend({ ... }); 
0
source

Source: https://habr.com/ru/post/1393700/


All Articles