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
submitMessagemethod to stop the default behavior by passing and using the event object:
Alternatively, change your button’ssubmitMessage: 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... }typefromsubmittobutton(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.successfor errors—switch that totoastr.errorand 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 settingintroLinesandoutroLines—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
emailis present—add theemailrule 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.logfile—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 beMAIL_PASSWORD=app password(quotes can cause issues with environment variable parsing). - Test mail sending via Tinker: Run
php artisan tinkerin your terminal and execute this test to validate your SMTP setup:
If this fails, you’ll get a direct error message pointing to the issue (e.g., invalid credentials, SMTP connection blocked by your host).Mail::raw('Test message from Laravel', function($msg) { $msg->to('your-personal-email@example.com')->subject('Laravel Mail Test'); }); - 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/sendMessagerequest:- 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.logfor 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
相关产品推荐
相关产品推荐

