我想在 React.js 中创建一个联系页面。单击提交按钮后,将使用 fetch
方法(使用 POST)调用 PHP 页面(在 Apache 上)。不幸的是,我不断收到以下错误(在我的 localhost:3000/dev 机器和 Apache 服务器上:
从源“http://localhost:3000”获取“http://example.com/dir/email.php”的访问已被 CORS 策略阻止:请求 header 字段内容类型为预检响应中的 Access-Control-Allow-Headers 不允许。
这是提交时调用的 sendEmail
函数:
sendEmail() {
fetch('http://example.com/dir/email.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'firstname': this.state.firstName,
'lastname': this.state.lastName,
'message': this.state.message
})
}).then(function(response) {
console.log(response);
return response.json();
}).then(function (json) {
console.log(json);
});
}
我的 PHP 脚本现在看起来像这样(我现在没有任何逻辑):
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
echo json_encode(array('success' => true));
我还尝试添加一个 .htaccess 文件,其中包含以下内容,但这似乎也不起作用:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Content-Type "*"
Header set Access-Control-Accept "*"
Header set Access-Control-Allow-Methods "GET, POST"
Header set Access-Control-Allow-Headers: X-Custom-Header
</IfModule>
我认为问题应该出在服务器上,因为我在 fetch
上找到的所有示例都看起来像我的。我搜索了这个问题,但我找到的答案不起作用或者适用于 Express 服务器。
也许还有其他更好的方法可以在 React.js 中创建像这样的简单联系表单,所以我愿意接受建议。我对 React.js 还很陌生,所以我很可能错过了一些明显的东西......
任何意见都将非常感激!
最佳答案
在发出 CORS 请求(即域名与 html 域不同的 AJAX/JSON/HTTP 请求)之前,浏览器将使用 OPTIONS 方法发送“飞行前请求”。
引用:https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
所以,把它放在你的 php 文件中:
<?php
// CORS support
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
if($_SERVER["REQUEST_METHOD"] == "OPTIONS") exit();
// before sending CORS request, modern browsers often make "pre-flight request" in order to see which headers are allowed/accepted from custom origin
// that request must be answered with status code 200 OK, and must contain header Acces-Control-Allow-Headers
说明:
- 预检请求旨在确保服务器了解该请求是 CORS 请求。
- “Access-Control-Allow-Header”列出了可在后续 CORS 请求中使用的所有 HTTP header
更详细的解释可以在上面的引用链接中阅读
关于javascript - React.js + PHP/Apache : Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703603/