简体   繁体   中英

Angular 5 and PHP Cannot POST to a server side file

I trying to send an encrypted variable from angular to php script for some test purposes.

Here is the client side script:

ngOnInit(){
let user = "am";
let key = "pizza";
let enc = crypto.AES.encrypt(user, key);
console.log(enc);
let dec = crypto.AES.decrypt(enc, key);
console.log(dec.toString(crypto.enc.Utf8));

const headerOptions = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const params = new HttpParams().set('name', enc)
this.http.post('aff.local/test.php', params, {
    headers: headerOptions
}).subscribe(
        res=>{
            console.log(res)
        },
        error=>{
            console.log( );
        }
    )
}

and the test.php script:

<?php
error_reporting(E_ALL);
ini_set('log_errors', 0);
ini_set('display_errors', 1);

$host = "localhost";
$db = "dentist";
$user = "root";
$pass = "root";

$conn = new PDO("mysql:host={$host};dbname={$db};", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
$enc = $_POST['name'];
echo $enc;
?>

I am having the following error in the response:

POST http://localhost:4200/aff.local/test.php 404 (Not Found)

and in the network tab:

Cannot POST /aff.local/test.php

The file do exist in the virtual host folder.

try this.

POST http: // localhost: 4200 / aff.local / test.php 404 (non trouvé)

**replace server angular(localhost:4200) by server php(ex: wamp: localhost:8080/folder name/filename)

localhost:8080 specifies the directory www of wamp server par defaut .

I found the solution by myself.

If you use just aff.local/test.php , angular will treat it as localhost:4200/yourlink automatically. Just add http://yourlink and it is fixed.

So the solution is http://aff.local/test.php and not aff.local/test.php :

ngOnInit(){
   let user = "am";
   let key = "pizza";
   let enc = crypto.AES.encrypt(user, key);
   console.log(enc);
   let dec = crypto.AES.decrypt(enc, key);
   console.log(dec.toString(crypto.enc.Utf8));

   const headerOptions = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
   const params = new HttpParams().set('name', enc)
   this.http.post('http://aff.local/test.php', params, {
       headers: headerOptions
  }).subscribe(
        res=>{
            console.log(res)
        },
        error=>{
            console.log( );
        }
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM