简体   繁体   English

如何使用 jQuery 将有效的 CSRF 令牌传递给 AdonisJs?

[英]How to pass a valid CSRF token to AdonisJs using jQuery?

I am using datatable edit and delete button and performing CURD operation but request can't get jquery ajax post id...我正在使用数据表编辑和删除按钮并执行 CURD 操作,但请求无法获取 jquery ajax 帖子 ID...

code Controller: QuestionController代码控制器:QuestionController

async findby({ request, response}) {
    response.send(request.input('id'));
  }

Jquery AJAX Post Request Code Jquery AJAX 发布请求代码

function QuestionEdit(id) {
  $.post(origin+'/dashboard/api/questions/findby', {id: id }, function(data){
      alert(data);
  });
}

Errors: HttpException EBADCSRFTOKEN: Invalid CSRF token错误: HttpException EBADCSRFTOKEN:无效的 CSRF 令牌

help me how to solve and post ajax request and get Adonis Js request...帮助我如何解决和发布ajax请求并获取Adonis Js请求...

You have to pass the token along with the request.您必须将令牌与请求一起传递。

  1. generate the token inside your view, you can put it on whatever you want, in the example below I'll store it as a data attribute:在你的视图中生成令牌,你可以把它放在任何你想要的地方,在下面的例子中,我将它存储为数据属性:
<div class="my-class" data-csrf-token="{{ csrfToken }}"></div>
  1. get it with jQuery and pass it in the post request:使用 jQuery 获取它并在 post 请求中传递它:
function QuestionEdit(id) {
  const token = $('.my-class').data('csrf-token');
  const params = { 
    id: id, 
    _csrf: token
  };

  $.post(origin + '/dashboard/api/questions/findby', params, function(data) {
    alert(data);
  });
}

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

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