【问题标题】:Angular client with with cors and phalcon api带有 cors 和 phalcon api 的 Angular 客户端
【发布时间】:2018-08-27 18:38:05
【问题描述】:

我使用 Angular 客户端向使用 CORS 的 phalcon API 发送请求。 GET 请求运行良好,但在 POST 请求中,我没有得到正文。它始终为空。

这是我的 Angular 客户端发布请求(它是一个测试函数,如果 api 也获取请求正文):

delete() {
  const tag = 'testclienttag';
  const body = {
    filename: 'test.txt',
    version: '2'
  };

  this.http.post(this.fileServerUrl + 'file/delete/' + tag, body, this.header())
    .subscribe(res => {
      console.log(res);
    });
}

private header() {
  const httpOptions = {
    headers: new HttpHeaders({
      'Accept': 'application/json',
      'Authorization': this.oAuthService.getAccessToken()
    })
  };
  return httpOptions;
}

这是请求的负载:

{
  filename: "test.txt",
  version: "2"
}

这是通过请求调用的 phalcon 函数:

public function deleteAction($tag) {
  $errors = [];
  $data = [];

  $data['tag'] = $tag;
  echo 'tag: '.$data['tag']."\n";
  if ((!is_null($tag)) && (!is_string($tag)))
    $errors['tag'] = 'String expected';

  if ($this - > request - > getPost('filename') != null) {

    $data['file_name'] = $this - > request - > getPost('filename');
    echo 'fileName: '.$data['file_name']."\n";
    if ($data['file_name'] != null) {
      if (!is_string($data['file_name']))
        $errors['file_name'] = 'String expected';
    }

  }

  if ($this - > request - > getPost('version') != null) {

    $data['version'] = $this - > request - > getPost('version');
    echo 'Version: '.$data['version'].
    "\n";
    if ($data['version'] != null) {
      if (!ctype_digit($data['version']) || ($data['version'] < 0))
        $errors['version'] = 'The version must be a positive Integer';
    }
  }...more code here but not relevant
}

这是 api 得到的:

{
  "tag": "testclienttag",
  "filename": null,
  "version": null
}

有人可以帮助我吗? 提前致谢

更新

解决了: 必须在 Api 端使用:$rawBody = $this->request->getJsonRawBody(true);

【问题讨论】:

    标签: angular cors phalcon


    【解决方案1】:

    对于使用 ng serve 进行开发,如果您使用的是 Angular CLI 6。我们可以配置 proxy.conf 它将充当您的后端 API 的代理并避免 CORS 错误。

    https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

    【讨论】:

    • 还有其他解决方案吗?
    【解决方案2】:

    Angular 的帖子似乎很可疑(tagbody 变量分隔似乎是 http.post 请求中的另一个参数)。是否可以在数组中传递参数,例如:

    const data = {
        tag: 'testclienttag',
        filename: 'test.txt',
        version: '2'
    };
    

    然后解析deleteAction中的data参数?

    【讨论】:

    • 有可能,我试过了。但我尝试从正文中获取标签、文件名和版本仍然为空。
    猜你喜欢
    • 2016-10-12
    • 2015-08-25
    • 2019-01-09
    • 2017-04-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2013-04-28
    • 2019-12-02
    相关资源
    最近更新 更多