doujiu3882 2017-05-01 20:40
浏览 60
已采纳

TokenMismatchException Laravel联系表单

I understand that you need a csrf_token() as posted in other questions/answers, but what if I was making calls from an external server that can't get the token?

First time building anything in Laravel. I am just building a simple ajax contact form to get familiarized with it.

Here's my JS (there will be some client side processing so I need individual values instead of just serializing it straight up)

$('#contact-form').on('submit', function(e){

    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: 'forms/contact.php',
        dataType: "json",
        data: {

            name: encodeURIComponent($("#contact-name").val()),
            email: encodeURIComponent($("#contact-email").val()),
            phone: encodeURIComponent($("#contact-phone").val()),
            subject: encodeURIComponent($("#contact-subject").val()),
            message: encodeURIComponent($("#contact-message").val())


        },
        success: function(data) {

            alert(data.message);

        }

    });

});

Here is my Route (which is in web.php)

Route::post('forms/contact.php', 'ContactController@send'); 

And here is my Contact Controller's main public function "send"

public function send(Request $request){

    return response()->json([
        'result' => true,
        'message' => 'success'
    ]);
}

Main goal right now is to just get a successful message back to the form.

...and would anyone know how I would return validation back to the form using something like this?

    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required'
    ]);

I apologize, I picked up Laravel yesterday so I'm super noob

  • 写回答

2条回答 默认 最新

  • drg14799 2017-05-01 20:45
    关注

    Laravel has a CRSF token that requires you to pass along a key to the POST call which is stored in the session. If this token does not match or does not exsist, it will refuse the request. You can read more about this here

    How to fix:

            name: encodeURIComponent($("#contact-name").val()),
            email: encodeURIComponent($("#contact-email").val()),
            phone: encodeURIComponent($("#contact-phone").val()),
            subject: encodeURIComponent($("#contact-subject").val()),
            message: encodeURIComponent($("#contact-message").val()),
            _token: "{{ csrf_token() }}"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加