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

Angular 5向Express传数据失败求助(subscribe方法未生效)

Hey there! Let's troubleshoot why your data isn't getting passed from Angular to Express via the subscribe method. Based on the code snippet you shared, here are the most common issues to check and fix:

1. Complete the Service Call & Add Error Handling

Your code cuts off at this.authService.updateProfileCompany(u...—first, make sure you're passing the right parameters and adding success/error callbacks to subscribe. This is critical because without error handling, you won't see why the request fails.

updateProfileCompany(e){ 
  var getUser = localStorage.getItem('user'); 
  getUser = JSON.parse(getUser);
  var id_student = getUser["id"]; 
  var nim = getUser["nim"]; 
  var nama = getUser["nama"]; 
  var email = getUser["email"]; 
  var id_company = this.company; 

  const user = { 
    id : id_student, 
    nama : nama, 
    email : email, 
    nim : nim,
    id_company: id_company // Include company ID in the payload!
  }; 

  console.log(user); 

  // Complete the service call with error handling
  this.authService.updateProfileCompany(user)
    .subscribe({
      next: (response) => {
        console.log("Profile updated successfully!", response);
        // Add post-success logic here (e.g., alert, redirect)
      },
      error: (error) => {
        console.error("Failed to update profile:", error);
        // This will show you exactly what went wrong (404, 500, missing data, etc.)
      }
    });
}
2. Verify Your AuthService Method

Make sure your AuthService is sending the request correctly to Express. Double-check the HTTP method, URL, and request headers:

// auth.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private apiUrl = "http://localhost:3000/api"; // Match your Express server URL

  constructor(private http: HttpClient) {}

  updateProfileCompany(userData: any): Observable<any> {
    // Set JSON content-type header (required for Express to parse the body)
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    // Use PUT for updates (or POST if your Express route uses POST)
    return this.http.put(`${this.apiUrl}/update-profile`, userData, { headers });
  }
}
3. Fix Your Express Endpoint

Ensure your Express server is configured to receive and parse the data correctly:

// Express route file (e.g., routes/profile.js)
const express = require('express');
const router = express.Router();

// Critical: Add this middleware to parse JSON request bodies
router.use(express.json());

// Match the HTTP method and URL from your Angular service
router.put('/update-profile', (req, res) => {
  // First, log the received data to confirm it's coming through
  console.log("Received data from Angular:", req.body);

  const { id, nama, email, nim, id_company } = req.body;

  // Add your database update logic here (example with Sequelize):
  // Student.update(
  //   { nama, email, nim, id_company },
  //   { where: { id: id } }
  // )
  // .then(() => res.status(200).json({ message: "Profile updated" }))
  // .catch(err => res.status(500).json({ error: err.message }));
});

module.exports = router;

Common Express pitfalls to fix:

  • Forgetting express.json() middleware (this makes req.body undefined)
  • Mismatched HTTP method (e.g., Angular uses PUT but Express uses POST)
  • Incorrect route URL (ensure it matches the one in your Angular service)
4. Check for CORS Issues

If Angular runs on localhost:4200 and Express on localhost:3000, you need to enable CORS in Express:

// Express app.js
const cors = require('cors');
app.use(cors()); // Allow all cross-origin requests (restrict to your domain in production)

Without CORS, the browser will block the request, and you'll see a cross-origin error in the console.

5. Validate Your this.company Value

Before sending the request, confirm this.company has a valid value:

console.log("Company ID to send:", this.company); // Check if it's undefined or empty

If this.company isn't properly bound to your UI input or state, you'll be sending an invalid id_company—which would make the update appear to do nothing.

内容的提问来源于stack exchange,提问作者Fatih

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:55:01