简体   繁体   English

Laravel 通过 axios React 发出 POST 请求时出现 419 错误

[英]Laravel 419 error on POST request via axios React

I'm trying to send a POST request to my API which is running Laravel 7.我正在尝试向运行 Laravel 7 的 API 发送 POST 请求。

My route is as follows:我的路线如下:

Route::get('/data', 'CartographieController@dataToJson');
Route::post('/addDraft', 'CartographieController@addDraft');

this is my post function in controller:这是我在 controller 中的帖子 function:

public function addDraft(Request $request)
{
    $draft = Draft::create($request->all());
    return response()->json($draft, 201);
}

I send the from React form here is:我在这里发送来自 React 的表单是:

handleAdd(event) {
event.preventDefault();

var draft = {
  description: this.state.description,
};

try {
  const nextData = clone(this.state);
  nextData.drafts.push(draft);
  //console.log("state" + this.state);
  this.setState({ drafts: nextData.drafts });
  console.log("state" + this.state);
} catch (error) {
  console.log(error);
}

axios
  .post("http://127.0.0.1:8000/addDraft/", this.state.drafts)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

As a response to the request I get: Request failed with status code 419作为对我得到的请求的响应:请求失败,状态码为 419

when it 419 mostly because you dont sent the csrf_token on the headers, do you?当它 419 主要是因为您没有在标题上发送 csrf_token 时,是吗?

put this on the head your html document把这个放在你的 html 文件的头上

<meta name="csrf-token" content="{{ csrf_token() }}">

and add headers x-csrf-token to your ajax并将标头 x-csrf-token 添加到您的 ajax

headers: {
    'x-csrf-token': document.querySelector("[name="csrf-token]").getAttribute('content')
}

Hi 419 is unproccesble entity error, better you can catch this error and display as exception error您好 419 是不可处理的实体错误,您可以更好地捕获此错误并显示为异常错误

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

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