Angular 2 个 http post 参数和正文

Angular 2 http post params and body

我正在尝试从我的 angular 应用程序进行 API 调用。我想要做的是使用命令参数向 API 发送 post 请求。我做了很多服务器端测试以及通过传出请求,$_POSTbody 数据永远不会存在。因此,我很确定问题出在这段代码中。

public post(cmd: string, data: object): Observable<any> {
    const params = new URLSearchParams();
    params.set('cmd', cmd);
    
    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      params: params,
      body: data,
      withCredentials: false
    });
    
    console.log('Options: ' + JSON.stringify(options));
    
    return this.http.post('http://t2w.dev/index.php', data, options)
      .map(this.handleData)
      .catch(this.handleError);
}

我已经尝试过许多不同的 JSON 结构,如 data 但这是我要发送的核心内容:

{
    "Username": "No thanks",
    "Password": "Donno"
}

this.handleDatathis.handleError是一种以数据和错误为参数的方法,而returns正是我想要的。

API 设置为记录通过 $_POST 的任何内容,当 运行 从除我的 angular 应用程序以外的任何地方请求时,它工作正常。到目前为止我做了什么:

  1. 传递原始查询而不是 URLSearchParams
  2. 传递没有正文的请求。
  3. 正在传递 RequestOptions 中的所有值。
  4. 将参数作为字符串传递。
  5. 传递正文作为参数。
  6. 传递正文为 JSON.stringify({ "Username": "No thanks", "Password": "Donno" }

Console output of RequestOptions

Options: {"method":null,"headers":{"Content-Type":["application/json"],"Accept":["application/json"],"X-CLIENT-ID":["380954038"],"X-CLIENT-SECRET":["5BgqRO9BMZ4iocAXYjjnCjnO7fHGN59WP8BTRZ5f"]},"body":"{}","url":null,"params":{"rawParams":"","queryEncoder":{},"paramsMap":{}},"withCredentials":false,"responseType":1} VM8529:1 XHR finished loading: POST "http://t2w.dev/index.php".

有没有人知道为什么数据永远不会发送?

http.post 的第二个参数是消息的 body,即有效载荷而不是 url 搜索参数。在该参数中传递 data

来自the documentation

post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response
    public post(cmd: string, data: object): Observable<any> {

        const params = new URLSearchParams();
        params.set('cmd', cmd);

        const options = new RequestOptions({
          headers: this.getAuthorizedHeaders(),
          responseType: ResponseContentType.Json,
          params: params,
          withCredentials: false
        });

        console.log('Options: ' + JSON.stringify(options));

        return this.http.post(this.BASE_URL, data, options)
          .map(this.handleData)
          .catch(this.handleError);
      }

编辑

您还应该检查第一个参数 (BASE_URL)。它必须包含您要访问的完整 url(减去查询字符串)。我提到是因为你给它起的名字,我只能猜测当前的值是多少(也许只是域?)。

也不需要在 http body.

中发送的 data/payload 上调用 JSON.stringify

如果您仍然无法到达终点,请在开发控制台中查看浏览器的网络 activity 以查看正在发送的内容。然后,您可以进一步确定是否使用正确的 header 和 body 调用了正确的终点。如果它看起来是正确的,那么使用 POSTMAN 或 Fiddler 或类似的东西来查看你是否可以通过这种方式到达你的端点(Angular 之外)。

是的,问题就在这里。这与您的语法有关。

尝试使用这个

return this.http.post(this.BASE_URL, params, options)
  .map(data => this.handleData(data))
  .catch(this.handleError);

而不是

return this.http.post(this.BASE_URL, params, options)
  .map(this.handleData)
  .catch(this.handleError);

此外,第二个参数应该是正文,而不是 url 参数。

它起作用了,谢谢@trichetriche。问题出在我的 RequestOptions 中,显然,您不能在使用 post 时将 paramsbody 传递给 RequestOptions。删除其中一个给我一个错误,删除两个并且它有效。仍然没有最终解决我的问题,但我现在有一些事情要做。最终工作代码。

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

好像你用的是Angular 4.3版本,我也遇到了同样的问题。将 Angular 4.0.1 和 post 与@trichetricheand 的代码一起使用,它会起作用。我也不确定如何在 Angular 4.3 :S

上解决它

假设我们的后端看起来像这样:

public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}

我们有一个这样的 HttpService:

    post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
        return this.http.post<T>(url, body, { headers: headers, params});
    }

以下是我们如何将正文和注释作为参数传递: // 如何调用它

const headers: HttpHeaders = new HttpHeaders({
    'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});

const bodyData = this.getBodyData(); // get whatever we want to send as body

let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');

this.httpService.post<any>(url, bodyData, headers, params);

它对我有用(使用 angular 7^),我希望对某些人有用。