You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Authorization header with value Bearer [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:

  1. Ensure the ID is being passed correctly
    In the component where you call getUserProfile, 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 undefined or empty, your URL becomes /api/userProfile/undefined, which will cause issues.

  2. Add Error Handling to Your Data Service
    Your current getUserProfile method 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.).

  3. Confirm Your Proxy Configuration is Active
    Make sure your Angular dev server is using the proxy config. Check your angular.json file:

    "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 /api requests will go to http://localhost:4200/api/... instead of your Node.js server, causing a 404 ("unknown url") error.

  4. Check the Auth Token
    Confirm this.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:17:28