我在尝试更新(或创建)记录时收到 Invalid CSRF token 错误。我正在使用 Elixir v1.0.3、Erlang/OTP 17 [erts-6.3] 和 Phoenix v0.8.0(我想,我不确定如何检查 Phoenix 的版本)。我正在创建一个 Web 应用程序,主要遵循 Phoenix 指南和 Elixir Dose Jobsite Example 资源。但是,当我尝试从 html 表单发布信息时,我收到 Invalid CSRF token 错误。按照错误中给出的建议,我将 'x-csrf-token': csrf_token 添加到操作中。
编辑.html.eex:
<h2>Edit Directory</h2>
<form class="form-horizontal" action="<%= directory_path @conn, :update, @directory.id, 'x-csrf-token': @csrf_token %>" method="post">
<div class="form-group">
<label for="directory" class="col-sm-2 control-label">Directory</label>
<div class="col-sm-10">
<input type="hidden" name="_method" value="PATCH">
<input type="text" class="form-control" value="<%= @directory.directory %>" name="directory" placeholder="Directory" required="required">
</div>
</div>
...
但我收到以下错误:
[error] #PID<0.579.0> running Ainur.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /config/directories/2?x-csrf-token=
** (exit) an exception was raised:
** (Plug.CSRFProtection.InvalidCSRFTokenError) Invalid CSRF (Cross Site Forgery Protection) token. Make sure that all your non-HEAD and non-GET requests include the csrf_token as part of form params or as a value in your request's headers with the key 'x-csrf-token'
(plug) lib/plug/csrf_protection.ex:54: Plug.CSRFProtection.call/2
(ainur) web/router.ex:4: Ainur.Router.browser/2
(ainur) lib/phoenix/router.ex:2: Ainur.Router.call/2
(plug) lib/plug/debugger.ex:104: Plug.Debugger.wrap/3
(phoenix) lib/phoenix/endpoint/error_handler.ex:43: Phoenix.Endpoint.ErrorHandler.wrap/3
(ainur) lib/ainur/endpoint.ex:1: Ainur.Endpoint.phoenix_endpoint_pipeline/2
(plug) lib/plug/debugger.ex:104: Plug.Debugger.wrap/3
(phoenix) lib/phoenix/endpoint/error_handler.ex:43: Phoenix.Endpoint.ErrorHandler.wrap/3
据我所知(刚接触 Elixir、Phoenix 和 HTML),“动作”本质上是一条路径,我在其中放置的任何参数都会找到返回应用程序的方式。而且,确实,我发现 x-csrf-token = "" 被传回路由器,所以 @csrf_token 一定不正确。我不确定 csrf_token 的确切来源,所以我不知道如何引用它(或者我这样做完全错误)。
任何想法将不胜感激。