Angular HTTPClient请求报错:无法读取undefined的length属性
Angular POST请求报错:TypeError: Cannot read properties of undefined (reading 'length')
错误日志
TypeError: Cannot read properties of undefined (reading 'length') at HttpHeaders.applyUpdate (http.mjs:222:27) at http.mjs:195:58 at Array.forEach (<anonymous>) at HttpHeaders.init (http.mjs:195:33) at HttpHeaders.forEach (http.mjs:263:14) at Observable._subscribe (http.mjs:2116:29) at Observable._trySubscribe (Observable.js:37:25) at Observable.js:31:30 at errorContext (errorContext.js:19:9) at Observable.subscribe (Observable.js:22:21)
我的请求代码
let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'}); this.http.post( '<target domain>', { grant_type: '<grant_type>', code: '<code>', redirect_uri: '<redirect_uri>', client_id: '<client_id>' }, { headers } ).subscribe({ next: (response) => { console.log('Token response:', response); }, error: (error) => { console.log('error:', error); } });
headers变量只是添加了Content-Type的默认HttpHeaders实例,看起来应该没问题,请问哪里错了?
解决方法
- 请求体格式不匹配:你设置了
Content-Type: application/x-www-form-urlencoded,但直接传了JSON对象作为请求体,Angular不会自动把JSON转成表单编码格式,这是触发报错的核心原因。 - HttpHeaders初始化的规范写法(可选优化):Angular的HttpHeaders是不可变对象,用
set方法添加头信息更规范,能避免一些潜在的不可变对象操作问题:let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
正确的请求写法
需要把请求体转换成URL编码的格式,两种常用实现方式:
方式1:用HttpParams构建请求体(推荐)
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'); const body = new HttpParams() .set('grant_type', '<grant_type>') .set('code', '<code>') .set('redirect_uri', '<redirect_uri>') .set('client_id', '<client_id>'); this.http.post('<target domain>', body, { headers }).subscribe({ next: (response) => console.log('Token response:', response), error: (error) => console.log('error:', error) });
方式2:手动拼接URL编码字符串
const headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'}); const body = `grant_type=${encodeURIComponent('<grant_type>')}&code=${encodeURIComponent('<code>')}&redirect_uri=${encodeURIComponent('<redirect_uri>')}&client_id=${encodeURIComponent('<client_id>')}`; this.http.post('<target domain>', body, { headers }).subscribe({ next: (response) => console.log('Token response:', response), error: (error) => console.log('error:', error) });
修改后请求体格式与Content-Type匹配,就能解决这个报错。
内容的提问来源于stack exchange,提问作者dcp3450
相关产品推荐
相关产品推荐

