发送POST请求获返回ID后订阅响应遇406错误的处理咨询
That 406 error is telling you your Angular client is requesting a response format your server can’t deliver. Let’s break down how to fix this:
1. Understand the Root Cause
Angular’s HttpClient defaults to sending an Accept: application/json header and expects JSON responses. If your server returns a raw numeric ID (like 123 instead of {"id": 123}), it can’t match that header—hence the "Not Acceptable" error.
2. Adjust the Service Request to Accept Plain Text
Modify your service’s POST method to explicitly accept plain text and convert the response to a number:
// student.service.ts addNewStudentTest(studentData: any): Observable<number> { return this.http.post('/your-api-endpoint', studentData, { responseType: 'text' // Tell Angular to expect plain text instead of JSON }).pipe( map(response => parseInt(response, 10)) // Convert text response to numeric ID ); }
3. Update Your Component Subscription
Now your component can directly use the numeric value without parsing issues:
// student.component.ts respData: number; addNewStudent() { this.studentService.addNewStudentTest(this.newStudentForm.value).subscribe( data => { this.respData = data; console.log(this.respData); }, err => { console.error('Request failed:', err); } ); }
4. Double-Check Server Configuration
Ensure your server sends the numeric ID with the correct Content-Type header. For plain text responses, it should set:
Content-Type: text/plain
If your server does return JSON (e.g., {"id": 123}), skip the responseType change and adjust your component to extract the ID from the JSON object:
// Component subscription for JSON responses data => { this.respData = data.id; // Pull the numeric ID from the JSON object console.log(this.respData); }
Why This Works
By setting responseType: 'text', you align your client’s expectations with what the server is actually sending (a raw number). The map operator converts the text string to a numeric value your component can use directly. This eliminates the header mismatch that caused the 406 error.
内容的提问来源于stack exchange,提问作者gbr

