javascript - How to handle X-CSRF-Token for jQuery POST in UI5? -
i want use jquery post method call xsjs service modifications in database.my xsaccess file prevents xsrf, need handle in controller method.
below controller code-
var obj= {}; obj.name= "john"; obj.age= "abc@xyz.com"; obj.loc= "minnesota"; jquery.ajax({ url: "servicetest.xsjs", type: "get", data: json.stringify(obj), beforesend: function(xhr) { xhr.setrequestheader("x-csrf-token", "fetch"); }, success: function(responsetoken, textstatus, xmlhttprequest) { var token = xmlhttprequest.getresponseheader('x-csrf-token'); console.log("token = " +token); jquery.ajax({ url: "servicetest.xsjs", type: "post", data: json.stringify(obj), beforesend: function(xhr) { xhr.setrequestheader("x-csrf-token", token); }, success : function(response) { // called once xsjs file sends response console.log(response); }, error : function(e) { // called in case of errors: var errmsg = e.responsetext console.log(e); } }); },
and here xsjs code-
var csrf_token = $.request.headers.get("x-csrf-token"); if(csrf_token === "fetch") { var content = $.request.body.asstring(); var args = $.parsejson(content); var xsname= args.name; var xsemail= args.email; var xsloc= args.loc; //then execute dml statement passing these 3 parameters arguments. catch (error) { $.response.setbody(content); $.response.status = $.net.http.internal_server_error; }
i not able update , getting error err 500 - internal server error. suggestions extremely helpful
edit:
if forgot token got 403 access denied error ("csrf token validation failed") , not 500 internal. think wrong services
you can add x-csrf-token header of post request setup ajax requests before fire post.
$.ajaxsetup({ headers: { 'x-csrf-token': token } }); jquery.ajax({ url: "servicetest.xsjs", type: "post", data: json.stringify(obj), beforesend: function(xhr) {
otherwise add each post request.
jquery.ajax({ url: "servicetest.xsjs", type: "post", data: json.stringify(obj), headers: { 'x-csrf-token': token }, beforesend: function(xhr) {
your way using beforesend event should work too.
Comments
Post a Comment