Skip to content Skip to sidebar Skip to footer

Cors Issue - Angular / Php / Apache

I think that there are plenty of similar topics here and there on the internet, but I did just spend 1h searching and still can't fix this. I cannot make a request with POST on my

Solution 1:

First you need to fix your POST data; you have square brackets around Object syntax.

const data = { 'prop1': 'value1', 'prop2': 'value2' };
this.http.post('http://localhost/distributor.php', data).subscribe(
  reply => {
    console.log(reply);
  },
  err => {
    console.log('error', err);
  });

Next, you need to add proper headers and set PHP up to deal with JSON:

<?php
header('Access-Control-Allow-Headers: Access-Control-Allow-Origin, Content-Type');
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json, charset=utf-8');

// grab JSON data sent by Angular$data = json_decode(file_get_contents('php://input'), true);
// add numeric data$data["prop3"] = 3;
// replyecho json_encode($data, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);

This worked for me.

Solution 2:

I had the same issue but it resolved by adding these lines to your php code

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Content-Type: application/json');

let data = {
            'prop1': 'value1',
            'prop2': 'value2'
        };
        returnthis.http.post('http://localhost/distributor.php', data, {headers: new HttpHeaders().set('Access-Control-Allow-Origin', '*')}).map((response: Response) => {
            let data = response;
            if (data) {
                console.log(data);
            }
        })

Post a Comment for "Cors Issue - Angular / Php / Apache"