跨端口调用Rest API失败:Spring Boot与网站跨域调用问题求助
Hey there, let’s tackle this cross-port API call issue you’re facing! The core problem here is Cross-Origin Resource Sharing (CORS)—browsers block requests from a different origin (different port, protocol, or domain) by default, which is why your AngularJS frontend on port 80 can’t reach your Spring Boot API on port 9090. The PHP cURL issue might be related too, so let’s break down the fixes step by step.
1. Resolve CORS on the Spring Boot API Side
This is the most critical fix, as CORS is enforced by browsers and your API needs to explicitly allow requests from your frontend’s origin.
Option 1: Global CORS Configuration (Recommended for All APIs)
Create a configuration class to enable CORS across your entire application:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); // Allow your frontend's origin (replace with your shared host URL, e.g., "http://your-domain.com") config.addAllowedOrigin("http://your-shared-host-url"); // Allow POST method (since your API uses POST) config.addAllowedMethod("POST"); // Allow necessary headers (including Content-Type) config.addAllowedHeader("*"); // Allow credentials if needed (e.g., cookies) config.setAllowCredentials(true); source.registerCorsConfiguration("/api/**", config); return new CorsFilter(source); } }
Note: For testing, you can use config.addAllowedOrigin("*"), but avoid this in production as it’s insecure.
Option 2: Controller-Level CORS Annotation
If you only need to enable CORS for this specific API endpoint, add the @CrossOrigin annotation to your controller method:
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DocumentController { @CrossOrigin(origins = "http://your-shared-host-url", allowedHeaders = "*", methods = org.springframework.web.bind.annotation.RequestMethod.POST) @PostMapping("/api/document/alldocuments") public ResponseEntity<?> getAllDocuments(@RequestBody SearchRequest search) { // Your API logic here return ResponseEntity.ok(response); } }
2. Fix Protocol Mismatch
I noticed your API uses https://****url****:9090 but your AngularJS code calls http://****url****:9090—this causes mixed content errors in browsers, which block the request. Make sure the protocol matches in both the API URL and your frontend code:
// Change from http to https (or vice versa to match your API's actual protocol) url: 'https://****url****:9090/aubwebsite-0.0.1-SNAPSHOT/api/document/alldocuments'
3. Improve AngularJS Request with Error Handling
Add error handling to your AngularJS code to debug exactly what’s going wrong (e.g., CORS errors, network issues):
$scope.getDocuments = function(){ var search = { pageNo : 1, studentId:"", studentName:"", rowPerPage:11 }; $http({ method: "POST", url: 'https://****url****:9090/aubwebsite-0.0.1-SNAPSHOT/api/document/alldocuments', data: $httpParamSerializerJQLike(search), headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(response) { console.log(response.data.documentList); if(response.data.documentList === undefined || response.data.documentList.length == 0){ $scope.documents = []; }else { $scope.documents = response.data.documentList; $scope.quantity = response.data.itemQuantity; } console.log($scope.documents,'All documents List'); console.log(response.data); }).catch(function(error) { // Log error details to debug console.error('API request failed:', error.status, error.statusText, error.data); }); }
4. Fix PHP cURL Issues
If your PHP cURL call is also failing, check these points:
- Match the protocol (http/https) with your API.
- Ensure cURL is configured to send the correct
Content-Typeand request body. - Add error handling to see what’s wrong:
<?php $apiUrl = 'https://****url****:9090/aubwebsite-0.0.1-SNAPSHOT/api/document/alldocuments'; $searchData = [ 'pageNo' => 1, 'studentId' => '', 'studentName' => '', 'rowPerPage' => 11 ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($searchData)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Only add these if you're using a self-signed SSL certificate (remove in production!) // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); if (curl_errno($ch)) { echo 'cURL Error: ' . curl_error($ch); } else { var_dump($response); } curl_close($ch); ?>
After applying these fixes, your AngularJS frontend should be able to call the Spring Boot API successfully, and your PHP cURL requests should work too.
内容的提问来源于stack exchange,提问作者Mahbub Ul Alam Shohag

