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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化