React js - Laravel 5:在 POST 方法中使用 csrf-token

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41968696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:14:09  来源:igfitidea点击:

React js - Laravel 5: Using csrf-token in POST method

javascriptlaravelreactjs

提问by Hiroki

I've read some questions about Laravel's CSRF, but I still haven't found how to use it with React. My goal is to make a POST form, where I make an AJAX call.

我已经阅读了一些关于 Laravel 的 CSRF 的问题,但我仍然没有找到如何在 React 中使用它。我的目标是制作一个 POST 表单,在那里我进行 AJAX 调用。

Here is an extract of my render( ).

这是我的render( ).

render() {
return (
  <form method="post" action="logpage">
   <input type="hidden" name="csrf-token" value="{{{ csrf_token() }}}" />
   //I'm sure this doesn't have csrf_token.

   <input type="text" name ="word" value={this.state.word || ''}/>
   <button onClick={this.submit} className="btn btn-flat btn-brand waves-attach waves-effect" data-dismiss="modal" type="button">Save</button>
  </form>
  );
}

Here is the submit function.

这是提交功能。

submit(){
fetch('/words', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
  body: JSON.stringify({
    //parameters
  })
}).then((response)=>{
  console.log(response);
});
}

The problem, I assume, is that $('meta[name="csrf-token"]').attr('content')is not being sent, because the token isn't generated. However, I don't see how I can generate it on React.

我认为问题$('meta[name="csrf-token"]').attr('content')在于没有发送令牌,因为没有生成令牌。但是,我不知道如何在 React 上生成它。

Does anyone have an idea?

有没有人有想法?

回答by EddyTheDove

You can echo the token in Javascript like this:

您可以像这样在 Javascript 中回显令牌:

<script> 
    var csrf_token = '<?php echo csrf_token(); ?>'; 
</script>

And access it from anywhere in Javascript

并从 Javascript 中的任何地方访问它

'X-CSRF-TOKEN': csrf_token

I hope this works for you.

我希望这对你有用。

回答by NULL pointer

You can also exclude some routes from csrf protection, meaning you don't need the token when posting to those routes, but you also risk cross site forgery posts on those routes.

您还可以从 csrf 保护中排除某些路由,这意味着您在发布到这些路由时不需要令牌,但您也有在这些路由上发布跨站点伪造帖子的风险。

To exclude, open app\Http\Middleware\VerifyCsrfToken.phpand you will see an $except array. Just add the route you wish to exclude to that array:

要排除,打开app\Http\Middleware\VerifyCsrfToken.php,您将看到一个 $except 数组。只需将您希望排除的路线添加到该数组中:

protected $except = [
  '/uploadtest'
];

I used this method when playing around with uploading files to AWS S3 store from a React Component, which avoided me needing to write a new blade template for the upload - I just put the form in the React Component, and added my POST route to the except array.

我在尝试从 React 组件上传文件到 AWS S3 存储时使用了这种方法,这避免了我需要为上传编写新的刀片模板 - 我只是将表单放在 React 组件中,并将我的 POST 路由添加到除了数组。

Once I got it "working" without csrf, I added it in by putting a global var definition in my blade template:

一旦我在没有 csrf 的情况下“工作”了它,我通过在我的刀片模板中放置一个全局 var 定义来添加它:

<head>
...
...
<script>
...
var csrf_token = '{{ echo csrf_token()}}';
...
</script>
</head>

and then included in in the form via the global variable - this worked! even though it 'should' be a prop, not a global variable:

然后通过全局变量包含在表单中 - 这有效!即使它“应该”是一个道具,而不是一个全局变量:

<form action="/uploadtest" method="POST" enctype="multipart/form-data">
  <input type="hidden" name="_token" value={csrf_token} />
  <input type="file" name="filename" />
  <input type="submit" value="Upload"/>
</form>

the 'better' way would be to pass the token in as a prop:

“更好”的方法是将令牌作为道具传递:

<form action="/uploadtest" method="POST" enctype="multipart/form-data">
  <input type="hidden" name="_token" value={this.props.csrf_token} />
  <input type="file" name="filename" />
  <input type="submit" value="Upload"/>
</form>