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:
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.) } }); }
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 }); } }
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 makesreq.bodyundefined) - Mismatched HTTP method (e.g., Angular uses PUT but Express uses POST)
- Incorrect route URL (ensure it matches the one in your Angular service)
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.
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

