当我提供响应标头时,为什么我的HTTPRequest被Cors阻止?

时间:2019-12-10 17:11:45

标签: post cors http-headers

我的Cpanel文件系统中有一个PHP脚本,试图将表单插入数据库。此表单包含一些字符串和1个大小不同的二进制字符串。

当我尝试在文件系统中发布到此PHP脚本时,出现以下错误。

XMLHttpRequest has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

我添加了以下标头,但似乎不起作用。它发生在Chrome和Firefox中,但POST在Edge中工作正常。

header("content-type: multipart/form-data");
header("access-control-allow-origin, *");
header("access-control-allow-credentials, true");
header("access-control-allow-methods, get,head,options,post,put");
header("access-control-allow-headers, access-control-allow-headers, origin,accept, x-requested-with, content-type, access-control-request-method, access-control-request-headers");

Chrome响应

enter image description here

边缘响应

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以看到响应中不包含CORS标头。

在我看来,您的PHP语法错误:

header('Content-type: multipart/form-data');
header("Access-Control-Allow-Origin", "*");
header("Access-Control-Allow-Credentials", "true");
header("Access-Control-Allow-Methods", "POST");
header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

肯定是:

header('Content-type: multipart/form-data');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

还不确定自从HTTP / 2(您正在使用)小写标头名称以来不同的大小写是否重要,但是您返回的是混合大小写。