带有Cors和Phalcon API的Angular客户端

时间:2018-08-26 09:22:09

标签: angular cors phalcon

我使用Angular客户端向与CORS配合使用的phalcon API发送请求。 GET请求工作得很好,但是在POST请求中,我没有得到正文。它始终为空。

这是我的有角度的客户端发布请求(它是一个测试功能,如果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
}

有人可以帮助我吗? 预先感谢

UPDATE

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

Angular帖子似乎令人怀疑(tagbody var分隔似乎是http.post请求中的另一个参数)。可以在数组中传递参数:

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

然后解析data中的deleteAction参数?