【问题标题】:Pass Object to Node JS GET request将对象传递给 Node JS GET 请求
【发布时间】:2020-01-10 18:22:38
【问题描述】:

我正在尝试将一个对象从我的 Angular 应用程序传递给我的 NodeJS 服务器。我可以在客户端很好地读取对象,但不能在服务器端。

这是我的客户端:

var query = {
  date: '9-2-2019',
  size: 4
}

this.http.get<any>(url, {params: {query: query} }).toPromise();

为什么我不能将它传递给我的 Node JS 服务器?

No overload matches this call.

是我的错。

【问题讨论】:

  • 请提供完整的错误信息和nodejs web服务代码。
  • 没有重载匹配这个调用。输入'{查询:{日期:字符串;尺寸:数量; }; }' 不可分配给类型 'HttpParams | { [参数:字符串]:字符串 |细绳[]; }'。
  • 请检查我的答案

标签: node.js angular http


【解决方案1】:

请将{ params: {query: query}} 更改为{params: query} 并将query.size 更改为字符串而不是数字

var query = {
  date: '9-2-2019',
  size: '4'
}


this.http.get<any>(url, {params: query}).toPromise().then(response => {
      console.log(response);
    })
    .catch(console.log);

另类

创建 // utils.service.ts

import { HttpParams } from '@angular/common/http';
// ...
export class UtilsService {
    static buildQueryParams(source: Object): HttpParams {
        let target: HttpParams = new HttpParams();
        Object.keys(source).forEach((key: string) => {
      const value: string | number | boolean | Date = source[key];
            if ((typeof value !== 'undefined') && (value !== null)) {
                target = target.append(key, value.toString());
            }
        });
        return target;
    }
}

然后在你的服务中使用它

import { UtilsService } from '/path/to/utils.service';

var query = {
  date: '9-2-2019',
  size: 4
}

 const queryParams: HttpParams = UtilsService.buildQueryParams(query);


this.http.get<any>(url, {params: queryParams }).toPromise().then(response => {
      console.log(response);
    })
    .catch(console.log);

【讨论】:

  • 我只是抄错了。现在关门了。
  • 使用then发送请求或订阅this.http.get&lt;any&gt;(url, {params: {query: query} }).subscribe(response =&gt; { console.log(response); })
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
相关资源
最近更新 更多