JS中XMLHttpRequest请求返回状态码0无内容,求排查MVC后端代码
Hey there! Let’s break down why your JavaScript GET request is returning status code 0 and no content—this usually means the browser aborted the request before getting a valid response from your backend. Here are the most likely fixes to try:
1. Fix CORS Configuration (Most Common Cause)
Status code 0 is a classic sign of a CORS (Cross-Origin Resource Sharing) error. If your frontend (e.g., running on http://localhost:3000) is making requests to a backend on a different origin (like http://localhost:5000), the browser blocks the response unless your backend explicitly allows cross-origin requests.
To set up CORS in ASP.NET:
- First, install the CORS package if you haven’t already:
Install-Package Microsoft.AspNetCore.Cors - Add CORS services in your
Program.cs(orStartup.csfor older versions):builder.Services.AddCors(options => { options.AddPolicy("AllowFrontend", policy => { policy.WithOrigins("http://your-frontend-url.com") // Replace with your actual frontend URL .AllowAnyMethod() .AllowAnyHeader(); }); }); - Apply the CORS middleware before routing:
app.UseCors("AllowFrontend"); app.UseRouting();
(For production, avoid AllowAnyOrigin()—restrict it to your trusted frontend URLs for security.)
2. Simplify Your Backend Controller Code
Your current code uses HttpResponseMessage, which isn’t the recommended approach in modern ASP.NET Core. Manual serialization can lead to unexpected issues, and the framework handles JSON serialization automatically. Here’s a cleaner, more reliable version:
[ProducesResponseType(typeof(Insider.Dto.CustomerDto), 200)] [HttpGet] public IActionResult Get() { var customers = service.GetCustomers(); return Ok(customers); // Automatically serializes to JSON with correct content headers }
This uses the built-in OkObjectResult to handle response formatting, which eliminates the need for manual StringContent and JSON serialization.
3. Verify Your Service Returns Valid Data
Double-check that service.GetCustomers() is actually returning data. If it’s returning null or an empty collection, you’ll get a 200 response with empty JSON—but that’s different from status code 0. Test the endpoint directly in your browser or using tools like Postman to confirm what response the server is sending.
4. Check Your Frontend Request Setup
Make sure your JavaScript request is formatted correctly. For example:
fetch('https://your-backend-url/api/customers') .then(response => { if (!response.ok) { throw new Error(`Server responded with ${response.status}`); } return response.json(); }) .then(data => console.log('Customers:', data)) .catch(error => console.error('Request failed:', error));
If there’s a CORS error, you’ll see a specific message about it in your browser’s developer console (under the Network or Console tab).
内容的提问来源于stack exchange,提问作者SharkyShark

