Angular 5与NodeJS按ID发起GET请求超时问题求助
Hey there! Let's break down why your Angular 5 GET request with an ID is timing out and throwing that "unknown url" error. I notice you suspect the frontend, but let's start with a critical backend issue I spotted, then move to frontend checks.
First: Fix Your Backend Controller Code
The biggest red flag here is your userProfileRead controller. User.findById(id) returns a single document object, not an array—but your code treats it like an array:
// ❌ This will fail because result is a single object, not an array const response = { count: result.length, // result.length is undefined for a single object data: result.map(...) // map() doesn't exist on objects! };
This will throw an error in your backend, causing a 500 status response. No wonder your frontend is timing out or failing! Here's the corrected version:
module.exports.userProfileRead = function(req, res, next) { const id = req.params.id; User.findById(id) .select(fields) .exec() .then((result) => { // If no user was found with the given ID if (!result) { return res.status(404).json({ message: `User with ID ${id} was not found` }); } // Format the single user into your expected response structure const response = { count: 1, data: [{ id: result._id, firstname: result.firstname, lastname: result.lastname, email: result.email, username: result.username }] }; res.status(200).json(response); }) .catch((err) => { console.log(err); res.status(500).json({ error: err }); }); };
Next: Verify the Backend API Works Manually
Before checking the frontend, confirm your backend endpoint works with a tool like Postman or curl:
- Send a GET request to
http://localhost:3000/api/userProfile/[valid-user-id] - Add an
Authorizationheader with valueBearer [your-jwt-token] - You should get a 200 response with the user data. If this fails, fix the backend first.
Now: Check the Angular Frontend
If the backend works manually, let's debug your Angular code:
Ensure the ID is being passed correctly
In the component where you callgetUserProfile, add a console log to confirm the ID is valid:// Example component code ngOnInit() { const userId = "your-valid-user-id"; // Or get from route params, etc. console.log("Fetching profile for ID:", userId); // Check this value! this.dataService.getUserProfile(userId).subscribe( profile => console.log(profile), err => console.error("Profile fetch error:", err) ); }If the ID is
undefinedor empty, your URL becomes/api/userProfile/undefined, which will cause issues.Add Error Handling to Your Data Service
Your currentgetUserProfilemethod doesn't handle errors, so you're missing critical details. Update it to log full error info:import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; // ... getUserProfile(id: string): Observable<UserProfile> { const url = `/api/userProfile/${id}`; console.log("Request URL:", url); // Verify the URL is correct return this.http.get<UserProfile>(url, { headers: { Authorization: `Bearer ${this.auth.getToken()}` } }).pipe( catchError(err => { console.error("Full error details:", err); return throwError(() => err); }) ); }This will show you exactly what's wrong (e.g., 404, 500, missing token, etc.).
Confirm Your Proxy Configuration is Active
Make sure your Angular dev server is using the proxy config. Check yourangular.jsonfile:"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-app-name:build", "proxyConfig": "src/proxy.conf.json" // Ensure this line exists! }, // ... }If this is missing, your
/apirequests will go tohttp://localhost:4200/api/...instead of your Node.js server, causing a 404 ("unknown url") error.Check the Auth Token
Confirmthis.auth.getToken()returns a valid, non-expired token. Log it before the request:console.log("Auth Token:", this.auth.getToken());If the token is missing or invalid, your backend will reject the request (likely with 401), which could manifest as a timeout or error.
Once you fix the backend controller and verify these frontend checks, your request should work as expected. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者cpayt03

