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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同