将对象传递给Node JS GET请求

时间:2019-09-08 22:48:19

标签: node.js angular http

我试图将对象从我的角度应用程序传递到我的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.

是我的错误。

1 个答案:

答案 0 :(得分:0)

请将{ 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);