AJAX向第三方RESTapi发布请求



。我使用laravel后端作为API,使用angular作为调用laravel API的前端。Laravel-api使用curl通过基本身份验证访问团队协作api。

现在我正在与团队合作Api。正在尝试使用API创建注释。API文件描述如下。

    {
  "comment": {
    "body": "Reply to earlier comment",
    "notify": "",
    "isprivate": false,
    "pendingFileAttachments": "",
    "content-type": "TEXT"
  }
}

//参考:http://developer.teamwork.com/comments#creating_a_commen

在我的ajax调用中,我使用了以下

  var data = $.param({
    'body' : commentBodyValue,  //variable
    'notify': "",
    'isPrivate':false,
    "pendingFileAttachments": "",
    "content-type": "TEXT"
  });

我的帖子没有给出错误,但也没有创建新的评论。我错过了什么?我想我没有按照api中允许的格式排列数据。你能帮我修一下吗?

编辑:

角度控制器:

//add new comment
$scope.addComment = function(taskId,commentAuthorId)
{
  var commentBod  = document.getElementById("commentBody");
  var commentBodyValue = commentBod.value;
  console.log("new comment : "+ taskId + commentBodyValue);
  //submit the post request
  //$http.post();
  //using jquery function param to serialize 
  var data = $.param({
    'body' : commentBodyValue,
    'notify': "",
    'isPrivate':false,
    "pendingFileAttachments": "",
    "content-type": "TEXT"
  });
  var config = {
      headers : {
          // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  }
  var url = "http://abounde.com/portal/api/post_comment/"+taskId;
  $http.post(url,data,config)
  .then(
    function(response){
      //success
      console.log("response : Submitted :D  " + response);
    },
    function(response){
      //failure
      console.log(response);
    }
  );
}

编辑2

Laravel路线和控制器路线://将评论发布到资源路由::post('post_comment/{task_id}'['使用'=>'PortalController@postComment','as'=>'portal.client.postComment']);

控制器:

    //post comment at task
        public function postComment(Request $request, $task_id)
        {
            $secretApiKey = $request->session()->get('secretApiKey');
            if(!empty($secretApiKey)){
            //post the msg
                $this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json");
            }else{
                return response()->json(['response'=>"Not Logged In"]);
            }           
        }

//authentication method
    public function callTeamworkApi($secretApiKey, $apiCallString)
    {
            //cURL
        $password = "xxx";
        $channel = curl_init();
        //options
        curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
        curl_setopt($channel, CURLOPT_HTTPHEADER,
                    array(
                      "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
        ));

        $msg = curl_exec($channel);
        curl_close($channel);
        return response()->json(['res'=>$msg]);
    }

编辑3:与团队合作联系Api支持。在他们的建议后,我想出了以下代码

  //post comment at task
    public function postComment(Request $request, $task_id)
    {
        $secretApiKey = $request->session()->get('secretApiKey');
        if(!empty($secretApiKey)){
        //post the msg
            $comment=array();
            // $comment['body']=$request->input('body');
            // $comment['notify']=$request->input('notify');          
            // $comment['isprivate']=$request->input('isprivate');
            // $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
            // $comment['content-type']=$request->input('content-type');

            $comment['comment']['body']="test";
            $comment['comment']['notify']="";
            $comment['comment']['isprivate']=false;
            $comment['comment']['pendingFileAttachments']="";
            $comment['comment']['content-type']="text";

            $this->callTeamworkPostApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
            //var_dump($comment);
            //return response()->json(['response'=>"Trying"]);
        }else{
            return response()->json(['response'=>"Not Logged In"]);
        }           
    }
}

///

  public function callTeamworkPostApi($secretApiKey, $apiCallString,$comment)
{
        //cURL
    $password = "xxx";
    $channel = curl_init();
    //options
    curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
    curl_setopt($channel, CURLOPT_HTTPHEADER,
                array(
                  "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
    ));
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);

    $msg = curl_exec($channel);
    curl_close($channel);
            var_dump($msg);
    //return response()->json(['res'=>$msg]);

}

var_dump($comment(给出

string(107) "{"comment":{"body":"test","notify":"","isprivate":false,"pendingFileAttachments":"","content-type":"text"}}"

然而,api仍然没有保存注释。这一定是一个curl post方法的问题。正确的

编辑4:我做了一个var_dump(curl_getinfo($channel((;

这给了我以下的回应。

array(26) { ["url"]=> string(55) "http://projects.abounde.com/tasks/8199861/comments.json" ["content_type"]=> NULL ["http_code"]=> int(500) ["header_size"]=> int(229) ["request_size"]=> int(311) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.5) ["namelookup_time"]=> float(0) ["connect_time"]=> float(0.109) ["pretransfer_time"]=> float(0.109) ["size_upload"]=> float(107) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(214) ["download_content_length"]=> float(0) ["upload_content_length"]=> float(107) ["starttransfer_time"]=> float(0.5) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "23.23.184.208" ["certinfo"]=> array(0) { } ["primary_port"]=> int(80) ["local_ip"]=> string(11) "192.168.0.6" ["local_port"]=> int(31657) }

响应代码500可以指出团队合作存在某种内部问题的事实。

我发现的问题是,你没有将从前端收到的评论数据传递给callTeamworkApi((中的curl请求。试试下面的代码,看看你是否得到了想要的输出

//post comment at task
    public function postComment(Request $request, $task_id)
    {
        $secretApiKey = $request->session()->get('secretApiKey');
        if(!empty($secretApiKey)){
        //post the msg
            $comment=array();
            $comment['body']=$request->input('body');
            $comment['notify']=$request->input('notify');          
            $comment['isPrivate']=$request->input('isprivate');
            $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
             $comment['content-type']=$request->input('content-type');

            $this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
        }else{
            return response()->json(['response'=>"Not Logged In"]);
        }           
    }

 //authentication method
public function callTeamworkApi($secretApiKey, $apiCallString,$comment)
{
        //cURL
    $password = "xxx";
    $channel = curl_init();
    //options
    curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
    curl_setopt($channel, CURLOPT_HTTPHEADER,
                array(
                  "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
    ));
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);

    $msg = curl_exec($channel);
    curl_close($channel);
    return response()->json(['res'=>$msg]);
}

找到的解决方案:在调用团队API时,将内容类型设置为Json是至关重要的。并且信息应该在头文件中。头变量应该是一个多数组,它接受身份验证和内容类型信息。

$headers = array();
$headers[] = "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password);
$headers[] = "Content-Type: application/json";

    //pass it as variable
    curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);

然后它就像魅力一样发挥作用。

在创建注释后返回following。

{"commentId":"4294639","STATUS":"OK"}

相关内容

  • 没有找到相关文章

最新更新