【问题标题】:Sendgrid API throwing a CORS error during testSendgrid API 在测试期间抛出 CORS 错误
【发布时间】:2020-12-04 17:31:54
【问题描述】:

大家下午好!尝试在 PHP 中测试 Sendgrid 时出现 CORS 错误。这是我的设置:

我有一个基于 Vue 的端,它调用一个普通的 PHP api 来完成一些基本任务。前端和 API 都位于 Amazon Lightsail 服务器上。在其中一个 PHP 文件中,我放置了 sendgrid 测试。注意:这个 api 是真正的香草,我手动设置了 sendgrid 文件,因为没有作曲家文件。这是调用发送网格功能时出现的错误:

Array
(
    [0] => HTTP/1.1 202 Accepted
    [1] => Server: nginx
    [2] => Date: Fri, 04 Dec 2020 16:51:19 GMT
    [3] => Content-Length: 0
    [4] => Connection: keep-alive
    [5] => X-Message-Id: X8jfBPyWS8eU0jhW5qWJrQ
    [6] => Access-Control-Allow-Origin: https://sendgrid.api-docs.io
    [7] => Access-Control-Allow-Methods: POST
    [8] => Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
    [9] => Access-Control-Max-Age: 600
    [10] => X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
    [11] => 
    [12] => 
)

是的,我阅读了提供的 cors 链接,但我认为它不适用于我的情况。这是相关的PHP:

ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_STRICT);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header("Content-type: application/json; charset=utf-8");
include_once '../lib/sendgrid-php/sendgrid-php.php';

在这之后是其他不考虑 SendGrid 方面的代码,所以我不会通过发布它来弄乱页面。下面是文件的 sendgrid 部分执行的地方:

$apiKey = "myapikey";
$email = new \SendGrid\Mail\Mail();
$email->setFrom("REALEMAIL", "Alert");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("TESTRECEIPTEMAIL", "MY NAME");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent("text/html", "<strong>and easy to do anywhere, even with PHP</strong>");
$sendgrid = new \SendGrid($apiKey);

try {
  $response = $sendgrid->send($email);
  print $response->statusCode() . "\n";
  print_r($response->headers());
  print $response->body() . "\n";
} catch (Exception $e) {
  echo 'Caught exception: '. $e->getMessage() ."\n";
}

首先要解决显而易见的问题:TESTRECEIPTEMAIL 和 REALEMAIL 是实际代码中的有效电子邮件,引用的 API 密钥是有效的 api 密钥。不,我不打算将 API 密钥留在文件中,就像我说的那样,我现在要做的就是让 sendgrid 先工作。

对此的任何见解将不胜感激。提前致谢!

【问题讨论】:

  • “我收到一个 CORS 错误” — 究竟是什么错误消息? CORS 仅与 JS 相关,您的问题中没有包含任何内容(除了顺便提及 Vue)。使用独立的 REST 客户端测试您的 PHP。它有效吗?然后担心让它与 JS 一起工作。如果出现错误,则调试 JS 和 your PHP。忘记 SendGrid 的结局吧。
  • 我应该更具体一点:我复制/粘贴了错误,因为我只是让 PHP api 将它转储到控制台。我确实只使用对 API 的直接调用来运行此测试,而不是源自 JS 前端,并得到与上图完全相同的 202 错误。

标签: php sendgrid sendgrid-api-v3


【解决方案1】:

我认为答案可能只是我对代码响应完全视而不见。看起来它实际上正在接受响应,但电子邮件永远不会发出,这是一个完全不同的问题。呃,浪费时间向大家道歉。

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    相关资源
    最近更新 更多