Angular 4中http.post请求调用失败问题排查求助
Hey there! Let's dig into why your POST request is landing in the error callback and get that comment data safely into your database. I'll walk through the most likely issues and fixes step by step.
First: Diagnose the Exact Error
Before guessing, let's get concrete details. Update your error callback to log the full error object—this will tell you exactly what's going wrong:
err => { console.error("Post failed. Details:", err.status, err.message, err.error); }
Then check your browser's Network tab (in DevTools) for the POST request:
- What's the HTTP status code? (404 = wrong PHP path, 500 = PHP server error, 400 = bad request data)
- What's in the "Response" tab? PHP might be outputting an error message here.
Common Frontend Issues
1. Incorrect Request Content-Type
Angular's HttpClient sends application/json by default, but PHP's $_POST superglobal only works with application/x-www-form-urlencoded (form data) or multipart/form-data. If your PHP code is trying to use $_POST['path'] etc., it'll get empty values, which might cause a server error.
Fix Option A: Send Form Data
Update your Angular code to send form-encoded data:
import { HttpParams, HttpHeaders } from '@angular/common/http'; // ... const formData = new HttpParams() .set('path', path) .set('author', authorInput) .set('comment', commentInput); this.http.post<CommentData>(submitScript, formData, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe( data => { console.log("Comment submitted successfully!", data); // No need to reassign data here—use the server's response instead }, err => { console.error("Post failed. Details:", err.status, err.message, err.error); } );
Fix Option B: Keep JSON, Update PHP to Read It
If you want to stick with JSON, keep your original Angular request but modify PHP to read the raw input:
// PHP code $rawData = file_get_contents('php://input'); $commentData = json_decode($rawData, true); if (!$commentData) { http_response_code(400); echo json_encode(['error' => 'Invalid JSON data']); exit; } // Now use $commentData['path'], $commentData['author'], $commentData['comment']
2. Wrong PHP File Path
Double-check that submitScript points to the correct location of your PHP file. For example, if your Angular app is running on http://localhost:4200 and your PHP file is at http://localhost/api/submit-comment.php, make sure submitScript is the full URL (or a correct relative path if they're on the same domain).
3. Unnecessary Data Reassignment
In your original code, you're overwriting the server's response data with your own local json object—this doesn't break the request, but it's useless. You should use the server's response (e.g., success message, new comment ID) instead.
Common PHP & Database Issues
- Database Connection Errors: Make sure your PHP code can connect to the database (check credentials, host, port).
- SQL Injection Risks: Never directly insert user input into SQL queries—use prepared statements to avoid attacks and syntax errors:
// Safe database insertion example with PDO $pdo = new PDO('mysql:host=YOUR_DB_HOST;dbname=YOUR_DB_NAME', 'USERNAME', 'PASSWORD'); $stmt = $pdo->prepare("INSERT INTO comments (path, author, comment) VALUES (?, ?, ?)"); $stmt->execute([$commentData['path'], $commentData['author'], $commentData['comment']]); echo json_encode(['success' => true]); - PHP Error Reporting: Enable error reporting temporarily to see server-side issues:
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
Start with checking the Network tab and error details—those will point you straight to the problem. Let me know if you find a specific status code or error message, and we can narrow it down further!
内容的提问来源于stack exchange,提问作者Rhodes

