Spring MVC结合Reactjs使用fetch请求报错问题求助
Let's break down why your form isn't working even though Postman does, and fix it step by step:
1. The Most Likely Culprit: Incorrect Fetch Data Format
Postman automatically formats application/x-www-form-urlencoded data correctly, but your frontend code is probably passing a plain JavaScript object instead of the required format. Browsers won't auto-convert objects to form data—you need to use URLSearchParams explicitly.
Fix Your Frontend Fetch Code
Replace your current data setup with this:
// Correctly format form data for x-www-form-urlencoded const data = new URLSearchParams(); data.append('firstname', document.querySelector('#firstname-input').value); // Replace with your actual input selector fetch('http://star-is.info:8080/app-1.0.0-BUILD-SNAPSHOT/register', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: data, // Add this only if your request needs to include cookies (like session data) credentials: 'include' }) .then(response => { // Always check if the response is OK first if (!response.ok) { throw new Error(`Server responded with ${response.status}`); } return response.json(); // Or response.text() if your backend returns plain text }) .catch(error => { console.error('Fetch failed:', error); });
2. Verify Your Backend CORS Configuration
Even though you added @CrossOrigin, double-check that it's configured to match your frontend's needs:
@CrossOrigin( origins = "http://star-is.info:8082", // Explicitly allow your frontend origin allowedHeaders = "*", // Allow all headers (or narrow it down if needed) methods = {RequestMethod.POST}, // Restrict to POST only allowCredentials = true // Required only if you're using credentials/cookies ) @PostMapping("/register") public ResponseEntity<?> handleRegistration(@RequestParam String firstname) { // Your registration logic here return ResponseEntity.ok("Registration successful"); }
3. Debug with Browser DevTools
To confirm what's going wrong:
- Open your browser's DevTools > Network tab
- Trigger the form submission
- Look for the
registerrequest:- If you see an
OPTIONSrequest first (preflight), check its status code. A 4xx/5xx here means your CORS config is missing something. - If the
POSTrequest goes through but returns an error, check the response body for server-side validation issues.
- If you see an
Why Postman Works But Your Frontend Doesn't
Postman skips some browser security checks (like CORS preflight for certain requests) and automatically formats form data correctly. Your frontend was likely sending JSON data instead of form-encoded data, which your backend isn't set up to parse—leading to a silent failure that manifests as a "failed to fetch" error.
内容的提问来源于stack exchange,提问作者Eshan I.

