PHP CORS 问题与 Axios Post 一起出现



我有一个简单的 post 请求,其中包含 axios 到 php 脚本,该脚本呈现一些 pdf 并应返回一个字符串。

现在我收到此错误:

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.

我在我的 php 文件中设置了这个:

<?php
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');

没有变化。 也试过这个:

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");

也没有变化。

我的 Axios 调用如下所示:

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);
        })

什么可以解决这个问题?

提前致谢

对我来说

一个可行的解决方案是:

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);
}

最新更新