【问题标题】:Parameter not passing in curl using Php参数未使用 PHP 传入 curl
【发布时间】:2019-04-22 10:16:58
【问题描述】:

我正在尝试使用 php 中的 curl 从 webservice(nodejs) 获取数据,但我得到的结果是“需要 lang” 我尝试使用以下代码,但在我错的地方不适合我? 这是我的代码

$post = ['lang'=> "593f973dea53161779dd5660",'password'=> "amit123d"];
  $ch = curl_init();
  $url="http://xxxxxx:8000/api/employer/login";
  curl_setopt($ch, CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  $response = curl_exec($ch);
  $result = json_decode($response);
  echo "<pre>";print_R($result);

【问题讨论】:

    标签: php node.js curl


    【解决方案1】:

    通常发送我使用的帖子变量:http_build_query 函数。

    $url = "http://xxxxxx:8000/api/employer/login";
    $post = ['lang'=> "593f973dea53161779dd5660",'password'=> "amit123d"];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    
    $response = curl_exec($ch);
    $result = json_decode($response);
    echo "<pre>";print_R($result);
    

    效果更好。

    【讨论】:

    • 使用打印 $_POST 变量的 php 文件的 url 检查您的代码。你会看到它正在工作。也许 NodeJS 网络服务正在等待与 POST 中的 lang 不同的东西,或者可能只是来自某个页面的 POST ....
    【解决方案2】:
    1. 首先检查请求是否发送post字段。
    $post = ['lang'=> "593f973dea53161779dd5660",'password'=> "amit123d"];
      $ch = curl_init();
      $url="https://httpbin.org/post";
      curl_setopt($ch, CURLOPT_URL,$url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      $response = curl_exec($ch);
      $result = json_decode($response);
      echo "<pre>";print_R($result);
    

    网站:https://httpbin.org/ 会在帖子数据存在时响应帖子字段。

    1. 我认为问题可能出现在nodejs方面。它是否正确检查了 post 字段? 根据我的经验,您的代码是正确的。

    【讨论】:

    • 不适合我,显示“需要 lang”,我该怎么办?
    猜你喜欢
    • 2016-09-21
    • 2018-07-08
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2011-09-23
    • 1970-01-01
    • 2015-06-23
    相关资源
    最近更新 更多