代码之家  ›  专栏  ›  技术社区  ›  Nate Reed

来自Node.js服务器应用程序的SendGrid CORS错误

  •  0
  • Nate Reed  · 技术社区  · 4 年前

    我只是想从SendGrid文档中得到一个简单的例子。这段代码是从我的Node.js+Express应用程序中调用的:

    function sendConfirmationEmail() {
        const sgMail = require('@sendgrid/mail');
        sgMail.setApiKey(process.env.SENDGRID_API_KEY);
        const msg = {
            to: '[email protected]', // Change to your recipient
            from: '[email protected]', // Change to your verified sender
            subject: 'Hello, world!',
            text: 'Thank you for your interest. We will let you know if we need any more information.',
            html: '<strong>Thank you for your interest. We will let you know if we need any more information.</strong>',
        };
        sgMail
            .send(msg)
            .then(() => {
                console.log('Email sent')
            })
            .catch((error) => {
                console.error(error)
            });
    }
    

    看到此记录:

    > { Error: Forbidden
        at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:146:29)
        at process._tickCallback (internal/process/next_tick.js:68:7)
      code: 403,
      message: 'Forbidden',
      response:
       { headers:
          { server: 'nginx',
            date: 'Sat, 27 Feb 2021 15:58:48 GMT',
            'content-type': 'application/json',
            'content-length': '281',
            connection: 'close',
            'access-control-allow-origin': 'https://sendgrid.api-docs.io',
            'access-control-allow-methods': 'POST',
            'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
            'access-control-max-age': '600',
            'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
         body: { errors: [Array] } } }
    
    

    不知道为什么这是CORS错误 发生在浏览器中。有什么想法吗?

    SendGrid建议的解决方法没有帮助:

    您可以创建一个基于服务器的应用程序,这将保护您的API密钥不被发布到世界各地。可以实现NodeJS、PHP、Ruby、Python、C#、Go和Java等语言,以便从锁定服务器环境的安全性中调用API。

    0 回复  |  直到 4 年前