2017-06-02 87 views
1

我的代码:TokenMismatchException错误

web.php

<?php 

/* 
|-------------------------------------------------------------------------- 
| Web Routes 
|-------------------------------------------------------------------------- 
| 
| Here is where you can register web routes for your application. These 
| routes are loaded by the RouteServiceProvider within a group which 
| contains the "web" middleware group. Now create something great! 
| 
*/ 

Route::get('/', function() { 
    return view('welcome'); 
}); 

Route::post('/xyz','[email protected]'); 

xyz.php

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

class xyz extends Controller 
{ 
    /** 
    * Store a newly created resource in storage. 
    * 
    * @param Request $request 
    * @return Response 
    */ 
    public function store(Request $request) { 
     $name = $request->name; 
     $email = $request->email; 
     $password = $request->password; 
     return response() 
      ->json(['name' => $name, 'email' => $email,'password' =>$password]); 
    } 
} 

我只要一运行这个API它给了我以下错误:enter image description here

在这里,我甚至没有使用表格,否则我可以插入cs rf_token。这个API有什么遗漏吗?

+2

将您的路由移至'api.php'并使用'api'前缀进行访问。网络路由使用'web'中间件组,它需要一个有效的csrf标记与每个表单请求一起传递。除非你创建这条路线与你的前端使用ajax,否则你不需要csrf检查。 – Sandeesh

+0

@Sandeesh我应该在网址或其他地方添加** api **前缀吗? –

+2

默认情况下,在'api.php'文件中定义的任何路由将以'api'作为前缀。所以你的路线将变成'http:// localhost:8000/api/xyz' – Sandeesh

回答

0

如果您正在使用Ajax请求必须添加:

headers : { 
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
      }, 

遵循以下步骤:

存储在你的根视图文件的顶部标记在“元”标签(布局/ app.blade.php)...

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

确保下载邮差拦截器(以邮差与浏览器同步?),并把它“上的”在浏览器和邮差两者。

https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo?hl=en

请在浏览器中您的应用程序的东西,打开控制台,并在头为csrf_token值搜索...

<meta name="csrf-token" content="cbpj1L7ym6fdPJhl5Fc0mH4MMU71gK1zatutgC3d"> 

内邮差添加页眉..

X-CSRF-TOKEN  cbpj1L7ym6fdPJhl5Fc0mH4MMU71gK1zatutgC3d 
+0

如果我通过邮递员检查,我该如何使它工作? –

+0

查看我的更新回答 – Rahul

+0

我在app.blade.php中加入了内容,并将标题内容与您说的一样,但仍然给出相同的错误 –

相关问题