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

发送POST请求获返回ID后订阅响应遇406错误的处理咨询

Fixing 406 (Not Acceptable) Error When Receiving Numeric ID from POST Request

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:32:25