duanjuebin2519
duanjuebin2519
2018-10-20 05:36

尝试使用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 dongxing2302 3年前

    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

    点赞 评论 复制链接分享

为你推荐