[英]Fetching wp_mail has been blocked by CORS policy
I'm building a headless wordpress site with Nextjs.我正在使用 Nextjs 构建一个无头 wordpress 站点。 I'm trying to make an api call to my wordpress CMS.我正在尝试对我的 wordpress CMS 进行 api 调用。
When fetching data from wordpress I can't get pass the cors.从 wordpress 获取数据时,我无法通过 cors。 Couldn't really find a way to add Access-Control-Allow-Origin to my api call.真的找不到将 Access-Control-Allow-Origin 添加到我的 api 调用的方法。 Ive been trying to do it like this, but still got the CORS error.我一直在尝试这样做,但仍然出现 CORS 错误。
$headers = array('Access-Control-Allow-Origin: *; Content-Type: application/json; Accept: application/json');
wp_mail('test@mail.com', 'subject', 'msg', $headers);
None of the headers you are dealing with are SMTP headers.您正在处理的标头都不是 SMTP 标头。 They should not go anywhere near the wp_mail
function.他们不应该在 wp_mail function 附近的任何地方使用wp_mail
。
CORS response headers ( Access-Control-Allow-*
) are HTTP response headers . CORS响应头( Access-Control-Allow-*
)是HTTP 响应头。
Generally with PHP, you need to add them to the HTTP response with the header()
function .通常使用 PHP,您需要使用header()
function将它们添加到 HTTP 响应中。
header("Access-Control-Allow-Origin: *");
Since you are using WordPress (which I'm not hugely familiar with), look at this answer as it seems to wrap itself around the normal headers API.由于您使用的是 WordPress(我不太熟悉),因此请查看此答案,因为它似乎将自身包裹在正常的标头 API 周围。
Content-Type: application/json
might an HTTP request or response header. Content-Type: application/json
可能是 HTTP 请求或响应 header。 It isn't clear from the context as your code snippet doesn't include anything to read the request body or generate the response body.从上下文中不清楚,因为您的代码片段不包含任何读取请求正文或生成响应正文的内容。
Accept: application/json
is an HTTP request header and needs to be sent from the browser to the server. Accept: application/json
是一个 HTTP 请求 header 并且需要从浏览器发送到服务器。 You shouldn't set it in PHP at all.您根本不应该在 PHP 中设置它。
I had the same problem a few months ago.几个月前我遇到了同样的问题。
Fixed it by adding the following code to the functions.php通过在函数中添加以下代码来修复它。php
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
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: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.