You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel联系表单发送邮件异常:POST无状态码且无报错页面刷新

Debugging Laravel Contact Form: No Errors, Page Refreshes on Submit

Let’s walk through how to diagnose and fix this issue—since you’re not seeing clear error messages, we’ll tackle each layer of your setup step by step.

1. Fix Frontend Form Submission Behavior (Immediate Page Refresh)

The most likely culprit for the instant page refresh is that your form is triggering the default browser submit action before your AJAX request completes. Here’s how to fix it:

  • Prevent default form submission: Modify your Vue submitMessage method to stop the default behavior by passing and using the event object:
    submitMessage: function(event){
        event.preventDefault(); // Add this line first to block default form submit
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
            }
        });
        // Rest of your AJAX code...
    }
    
    Alternatively, change your button’s type from submit to button (since you’re handling submission via Vue):
    <button type="button" class="btn btn-default" v-on:click="submitMessage">Send Message</button>
    
  • Improve error logging: Your current error handler uses toastr.success for errors—switch that to toastr.error and log detailed error info to the console for debugging:
    error: function(error){
        console.log('AJAX Error Details:', error); // Check this in DevTools Console
        toastr.error(error.responseJSON?.error || 'An unknown error occurred');
    }
    
  • Verify CSRF token presence: Ensure you have this meta tag in your HTML <head> (required for Laravel’s CSRF protection):
    <meta name="csrf-token" content="{{ csrf_token() }}">
    

2. Fix Critical Backend Code Errors

Looking at your controller and Mailable code, there’s a clear syntax mistake that will break email sending, plus opportunities to add better error tracking:

  • Fix Mailable variable assignment: You have extra $ symbols when setting introLines and outroLines—this is invalid PHP. Update your Mailable constructor:
    public function __construct($user, $email, $message) {
        $this->title = 'Contact from' . ' ' . $user;
        $this->introLines = ['The following user has issued a message']; // Removed extra $
        $this->outroLines = ['User: ' . $user, 'Email: ' . $email, 'Message: ' . $message]; // Removed extra $
    }
    
  • Add email format validation: Your current validation only checks that email is present—add the email rule to catch invalid addresses:
    $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email', // Add |email here
        'message' => 'required'
    ]);
    
  • Wrap email sending in try/catch for error logging: Mail sending can fail silently if exceptions aren’t caught. Add this to your controller method to capture and log issues:
    public function sendMessage(Request $request){
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required'
        ]);
    
        \Illuminate\Support\Facades\Log::info('Contact form submitted', $request->all()); // Log incoming request data
    
        $users = User::all();
        $emails = collect($users)->pluck('email')->all();
    
        $user = Auth::check() ? Auth::user()->getFullName() : $request->input('name');
        $email = Auth::check() ? Auth::user()->email : $request->input('email');
        $message = $request->input('message');
    
        try {
            Mail::to($emails)->send(new Contact($user, $email, $message));
            Mail::to($email)->send(new ContactConfirm($user, $email, $message));
            return response()->json(['response' => 'Email Successfully Sent']);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Email sending failed: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
            return response()->json(['error' => 'Failed to send email: ' . $e->getMessage()], 500);
        }
    }
    
  • Check Laravel logs: After making these changes, look at your storage/logs/laravel.log file—this will show you any backend errors, including validation failures, mail sending issues, or syntax mistakes.

3. Verify Email Configuration

Even if you updated .env and config/mail.php, let’s confirm your setup works reliably:

  • Remove quotes from MAIL_PASSWORD: In your .env, MAIL_PASSWORD='app password' should be MAIL_PASSWORD=app password (quotes can cause issues with environment variable parsing).
  • Test mail sending via Tinker: Run php artisan tinker in your terminal and execute this test to validate your SMTP setup:
    Mail::raw('Test message from Laravel', function($msg) {
        $msg->to('your-personal-email@example.com')->subject('Laravel Mail Test');
    });
    
    If this fails, you’ll get a direct error message pointing to the issue (e.g., invalid credentials, SMTP connection blocked by your host).
  • Confirm Gmail App Password: Ensure you’ve enabled 2FA on your Gmail account and generated a valid App Password (regular passwords won’t work for SMTP if 2FA is enabled).

4. Debug Network Requests

In your browser’s DevTools (F12):

  • Go to the Network tab and check the Preserve log checkbox (this keeps requests visible after page refresh).
  • Submit the form and look for the POST /pages/contact/sendMessage request:
    • If the request shows as Cancelled: The default form submission is still happening (fix step 1).
    • If you see a 422 status: Validation failed—check the response body for which fields are invalid.
    • If you see a 500 status: A server error occurred—check laravel.log for details.
    • If you see a 200 status but no success message: Verify your toastr library is correctly included and initialized on your page.

内容的提问来源于stack exchange,提问作者I Love Code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:16:31