Skip to content
Advertisement

php cors issue with axios post

I have a simple post request with axios to php script which renders some pdfs and should return a String.

Now I got this error:

Access to XMLHttpRequest at 'IP:7580/pdfgen/pdfGen.php' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

I set this in my php file:

<?php
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');

With no changes. also tried this:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");

also no changes.

my axios call looks like this:

axios.post("http://IP:7580/pdfgen/pdfGen.php", this.state)
        .then(response => {
            report = {...this.state.report};
            report.createdAt = reportCreatedAt;

            window.open(response.data);


            this.setState({report: report, pdf: response.data});
            console.log(response);
        })

What could solve this?

Thanks in advance

Advertisement

Answer

A working solution for me is:

if (isset($_SERVER['HTTP_ORIGIN'])) {
    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
    // you want to allow, and if so:
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 1000');
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
        // may also be using PUT, PATCH, HEAD etc
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
    }

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
        header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization");
    }
    exit(0);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement