duanjuebin2519 2018-10-20 05:36
浏览 73
已采纳

尝试使用Angular将数据通过POST发送到cURL

I'm trying to send data but it fails everytime.
Smehow when i send it from Angular to cURL it says Undefined Index (which i know most likely the variable is empty or isn't sending)

inicio.ts:

insertar() {
   this.fname = this.Form.value.fname;
   this.email = this.Form.value.email;
    this.http.post('http://localhost/curl/config/config.php', {
      fname : this.fname,
      email: this.email,
    }).subscribe((data: any) => {
      console.log(data);
      this.router.navigate(['/inicio']);
    }, error => {
       console.log(JSON.stringify(error));
    });
  } 

config.php

<?php

# An HTTP GET request example
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth- 
Token');
header('Content-Type: application/x-www-form-urlencoded');
$method = $_SERVER['REQUEST_METHOD'];
$url = 'http://localhost/curl/api/rest.php';
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true); 
print_r($data);

if(isset($_POST['fname']) && $_POST['email']){
    $data = [
        "fname" => $_POST['fname'],
        "email" => $_POST['email'],
        ];
}

if(isset($_POST['id'])){
$id = [
    "id" => $_POST['id']];
}


switch ($method) {
    case 'GET':
         // not ready
        break;
        case 'POST':
        postData($url,$method,$data);
        break;
        case 'PUT':
        # code...
        break;
        case "DELETE":
         // not ready
        break;

    default:
        //echo json_encode(['Error'=>'Un Error ha ocurrido']);
        break;
}
function postData($url,$method,$data){
   $ch = curl_init();
   curl_setopt($ch,CURLOPT_URL, $url);
   curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
   curl_setopt($ch,CURLOPT_POST, 1);
   curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($data));
   $response = curl_exec($ch);

   if(!$response){
       return false;
   } else {
      print_r($response);
   }
   curl_close($ch);

}

So i'm missing something in my php file? because i think there's something which stops or doesn't recognize the data i'm sending it.
Edit: if i use terminal and i execute

curl -X POST <url> -d param:value -d param2:value2

it works

Second Edit: Now it works in the config.php file but when i'm trying to send the information from $data it sends empty.

API code:

<?php 

header('content-type:application/json');
header('Access-Control-Allow-Origin: *');
include ('../config/conn.php');

$method = $_SERVER['REQUEST_METHOD'];

$postdata = file_get_contents("php://input");



switch ($method) {
    case 'GET':
        get($conexion);
        break;
    case 'POST':
        post($conexion,$postdata);
        break;
    case 'PUT':
        put();
        break;
    case 'DELETE':
       delete($conexion,$postdata);
        break;    

    default:
        # code...
        break;
}


function get($conexion){

   $sql = 'SELECT * FROM tbl_users';
$resultado = pg_query($conexion,$sql);
while ($rows = pg_fetch_array($resultado)) {
    $array[] = $rows;
}
echo json_encode($array);
}



function post($conexion,$postdata){
//It displays as empty string
echo $postdata;

 /*
$sql = "INSERT INTO tbl_users(fname,email) VALUES('".$fname."','".$email."')";
 $resultado = pg_query($conexion,$sql);  
 close($conexion);  
 */   
}

function put(){

}
function delete($conexion,$postdata){
    parse_str($postdata, $arr);
    $idn = $arr['id'];
    $id = (int)$idn;
    echo $id;


}

function close($conexion){
    pg_close($conexion);
}


 ?>
  • 写回答

1条回答 默认 最新

  • dongxing2302 2018-10-20 06:37
    关注

    When postign json content, you cannot use $_POST variable

    Try something like this

    $jsonBody= file_get_contents('php://input');
    $data = json_decode($jsonBody, true); 
    

    $data should be an associative array with fname and email keys

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov5中的val测试集训练时数量变小问题
  • ¥15 MPLS/VPN实验中MPLS的配置问题
  • ¥15 materialstudio氢键计算问题
  • ¥15 已知隐函数其中一个变量的,求另外一个变量
  • ¥15 echarts图表制作
  • ¥15 halcon根据玻璃面板纹路取区域
  • ¥15 HFSS设计小型化180度耦合器
  • ¥15 使用CInternetSession,CHttpFile读取网页文件时有些电脑上会卡住怎么办?
  • ¥15 水下机器人的半物理仿真研究
  • ¥15 微服务假死,一段时间后自动恢复,如何排查处理