Angular access 4 to php does not receive the JSON

2

Good day, I have a problem, I have my file JSON by xampp, and effectively this code extracts the data I need in JSON . In the part of PHP , if you receive files JSON and insert them into the database very well, but when working with angular, I send you the data that I collect in HTML , which effectively combierte in JSON but does not pass these files JSON to PHP for you to insert them into the database.

The variable this.url=" link "

The link of the index is the url + Datos_Sencibilizacion

and show that if you find the JSON that I want to see in angular or that I also want to import it to PHP to insert it

getSencibilizacion(): Observable < SencibilizacionModel[] > {
  return this._http
    .get(this.url + 'Datos_Sencibilizacion')
    .map((res: Response) => res.json())
    .catch((error: any) => Observable.throw(error.json().error))
}



//SECCION POST


postSencibilizacion(Dato_sencibilizacion: SencibilizacionModel) {
  let json = JSON.stringify(Dato_sencibilizacion);
  let params = 'json=' + json;
  let headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  let options = new RequestOptions({
    headers: headers
  });

  return this._http
    .post(this.url + 'Datos_Sencibilizacion', params, options)
    .map((res: Response) => res.json())
    .catch((error: any) => Observable.throw(error.json().error))
}
public logout(): void {
  console.log(this.authenticationService.logout()) this.authenticationService.logout().subscribe( response=> {
    if(response) {
      console.log(response);
      this.storageService.logout();
    }
  }
  );
}

;
onSubmit() {
  this.sencibilizacionService.postSencibilizacion(this.Dato_sencibilizacion).subscribe( response=> {
    if(response.code==200) {
      this.authenticationService.logout();
    }
    else {
      console.log(response);
    }
  }
  , error=> {
    console.log(<any>error);
  }
  );
}

;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?php

require_once 'vendor/autoload.php';

$app = new \Slim\Slim();

$serverName = '****';
$connectionInfo = array( "database"=>"***", "UID"=>"***", "PWD"=>"***", "Characterset"=>"UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);


//Configuracion de Cabeceras
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
    die();
};


$app->get('/Datos_Sencibilizacion', function() use($conn, $app){
	$sql = 'SELECT * FROM Datos_Sencibilizacion;';
	$insert = sqlsrv_query ($conn, $sql);

$rows = array();
while( $row = sqlsrv_fetch_array( $insert, SQLSRV_FETCH_ASSOC)){  
		$rows[] = $row;
}

	$result = array(
			'status' => 'success',
			'code'	 => 200,
			'data' => $rows
		);

	echo json_encode($result);
});



$app->post ('/Datos_Sencibilizacion', function() use($app, $conn){
    
	$json = $app->request->post('json');
	$data = json_decode($json, true);


    if(!isset($data['Fecha'])){
        $data['Fecha']="NULL";
    }
    if(!isset($data['Nobre_Propietario'])){
        $data['Nobre_Propietario']="NULL";
    }
    if(!isset($data['Nobre_Establecimiento'])){
        $data['Nobre_Establecimiento']="NULL";
    }
    if(!isset($data['Direccion_Establecimiento'])){
        $data['Direccion_Establecimiento']="NULL";
    }
    if(!isset($data['Actividad_Economica'])){
        $data['Actividad_Economica']="NULL";
    }
    if(!isset($data['Telefono_Propietario'])){
        $data['Telefono_Propietario']=0;
    }
    if(!isset($data['Firma'])){
        $data['Firma']="0";
    }

    
                
    $query = "  INSERT INTO Datos_Sencibilizacion
                VALUES (".
                "'{$data['Fecha']}',".
                "'{$data['Nobre_Propietario']}',".
                "'{$data['Nobre_Establecimiento']}',".
                "'{$data['Direccion_Establecimiento']}',".
                "'{$data['Actividad_Economica']}',".
                "{$data['Telefono_Propietario']},".
                "'{$data['Firma']}'".
                ");";
    
	
    $insert = sqlsrv_query ($conn, $query);
	
        $result = array(
            'status' => 'error',
            'code' => 404,
            'message' => 'Dato NO creado correctamente'
    );

    if($insert){
        $result = array(
            'status' => 'success',
            'code' => 200,
            'message' => 'Dato creado correctamente'
        );
    }
    echo json_encode ($result);
});

$app->run();

?>

In this case the login of my project will be damaged, by removing the CoreModule library Would you open a solution to leave the login without this library?

    
asked by DaVid Roa 27.07.2017 в 00:39
source

3 answers

1

Good afternoon tracking I found that this fake-backend.ts function is the one that harms my program. but I need it for the login, I do not know if I could adapt it so that it does not generate problems, could someone help me? //

import {Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod, ResponseType} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {User} from "../models/user.model";
import {USERS} from "../mocks/mock-users";

class MockError extends Response implements Error {
  name:any;
  message:any;
}

export function fakeBackendFactory (backend: MockBackend, options: BaseRequestOptions) {
  backend.connections.subscribe((connection: MockConnection) => {
    setTimeout(() => {
      // fake authenticate api end point
      if (connection.request.url.endsWith('/api/authenticate/login') && connection.request.method === RequestMethod.Post) {
        let params = JSON.parse(connection.request.getBody());

        // check user credentials and return fake jwt token if valid
        let found: User = USERS.find((user: User) => {return (params.username === user.username);});
        if (found) {
          if(params.password === found.password) {
            connection.mockRespond(new Response(
              new ResponseOptions({status: 200, body: {token: 'fake-token-jwt', user: found}})
            ));
          }else{
            connection.mockError(new MockError(new ResponseOptions({type:ResponseType.Error, status:400, body: JSON.stringify({code: 2, message: 'The password does not match '})})));
          }
        } else {
          connection.mockError(new MockError(new ResponseOptions({type:ResponseType.Error, status:400, body: JSON.stringify({code: 1, message: 'Username does not exists'})})));
        }

      }

      if (connection.request.url.endsWith('/api/authenticate/logout') && connection.request.method === RequestMethod.Post) {
        let params = JSON.parse(connection.request.getBody());
        connection.mockRespond(new Response(
          new ResponseOptions({status: 200, body: true})
        ));
      }
    }, 500);

  });

  return new Http(backend, options);
}

export let fakeBackendProvider = {
  // use fake backend in place of Http service for backend-less development
  provide: Http,
  useFactory: fakeBackendFactory,
  deps: [MockBackend, BaseRequestOptions]
};
    
answered by 01.08.2017 в 00:21
1

I recently did a login with ionic, it's almost equal to angular, since you ask me for a possible example here.

On the client's side you can do something like:

let email = "[email protected]";
let password = "var_password";

this.http.post("url del archivo del servidor", 
  '{"task":"login", "data":{"email":"' + email + '","password":"' + password + '"}}')
  .subscribe(response => {
   console.log(response);
   let data = JSON.parse(response["_body"]);
   console.log("Has algo con lo que regreso el servidor: " + data);
 }, fail => {
    console.log(fail);
 });

In the server part with php:

<?php
// Estos renglones los usa google chrome para cuestiones de seguridad.
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache por un dia
}
// Los encabezados Access-Control se reciben durante las peticiones OPTIONS
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

// Aqui empieza el codigo interesante.
include_once "tu conexion sql";
// file_get_contents("php://input") toma cualquier valor que entre por POST.
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
    $request = json_decode($postdata);
    switch ($request->task) {
        case 'login':
            // se espera un json como: {"task": "login", "data": {"email": "email", "password": "password"}}
            echo login($conn, $request->data);
            break;
        case 'otro_caso':
            // En otro_caso diferente de login
            break;
        default:
            echo json_encode("No se realizo ninguna accion");
            break;
    }
}
/**
 * Selecciona en de la base de datos la información correspondiente al correo 
 * electrónico y contraseña que se envió y compara la contraseña en la consulta con la que regreso de sql,
 * si coinciden se le regresa al usuario su información.
 * @param type $conn Es un objeto con la información para la conexión a la base de datos.
 * @param type $query Es la información de la consulta a realizar.
 * @return String Regresa la información del usuario o un mensaje de error.
 */
function login($conn, $data) {
    $query = $conn->query("SELECT id, name, password, email FROM usuarios WHERE email = '".$data->email."';");
    if ($query->num_rows > 0) {
        while($fila = $query->fetch_array(MYSQLI_ASSOC)) {
            $temp = array();
            foreach ($fila as $i => $valor) {
                $temp[$i] = utf8_encode($valor);
            }
            $resultd_arr[] = $temp;
        }
        $query->free();
        $conn->close();
        if ($resultd_arr[0]["password"] == $data->password){
            // todo correcto
            return json_encode('{"id": "'.$resultd_arr[0]["id"].'", "name": "'.$resultd_arr[0]["name"].'", "email": "'.$resultd_arr[0]["email"].'"}');
        } else {
            // password incorrercto
            return json_encode("incorrecto");
        }
    } else {
        // email incorrecto
        return json_encode("incorrecto");
    }
}
?>
    
answered by 01.08.2017 в 03:03
0

This part is badly written:

let params = 'json=' + json;

By saving that text so it is no longer a json, the right thing would be something like this:

let params = '{"json":' + json + '}';
    
answered by 01.08.2017 в 01:39