Node.js中用Fetch调用Laravel API无法获取HTTP错误信息求助
I've run into this exact issue before with Fetch and Laravel APIs—let's break down why this is happening and how to fix it.
The Root Cause
Unlike curl, which automatically returns the response body regardless of HTTP status code, the Fetch API has a key quirk: it only rejects promises on network failures (like a failed connection), not on HTTP error status codes (4xx/5xx). So when Laravel returns your 020102 error with a 4xx status code (likely 409 Conflict), Fetch still resolves the promise but marks response.ok as false. If you're only parsing JSON when response.ok is true, you'll miss the error payload entirely.
Example of Problematic Fetch Code
Chances are your current code looks something like this, which won't capture the Laravel error:
fetch('http://localhost:8080/api/signup', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'xyz', password: 'xyz', filterZip: '123123' }) }) .then(response => response.json()) // Only runs for 2xx status codes .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // Only catches network errors
The Fix: Handle All Responses Explicitly
You need to parse the response body first, then check if the request was successful. Here's the corrected code that will capture the Laravel error:
fetch('http://localhost:8080/api/signup', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'xyz', password: 'xyz', filterZip: '123123' }) }) .then(response => { // Parse the response body FIRST, no matter what the status code is return response.json().then(data => { // Check if the HTTP status code was successful if (!response.ok) { // Throw an error containing the full Laravel error payload throw new Error(JSON.stringify(data)); } return data; }); }) .then(successData => { console.log('Signup successful:', successData); }) .catch(error => { // Parse the error message to access Laravel's error details const apiError = JSON.parse(error.message); console.error('Signup failed:', apiError.error.message); console.error('Error Code:', apiError.error.errorCode); });
Additional Checks to Match Curl Behavior
Double-check these details to ensure your Fetch request is identical to the curl call:
- Headers: Confirm
Content-Type: application/jsonis correctly set (your code looks good here) - Request Body: Make sure
JSON.stringifyis used properly, with no typos in field names (likefilterZip) - URL Access: Ensure your Node.js environment can reach
http://localhost:8080(no firewall or network restrictions blocking the request)
By explicitly handling all responses and parsing the body before checking status, you'll capture that Laravel error payload just like curl does.
内容的提问来源于stack exchange,提问作者Sarfraz

