NodeJS SendGrid CORS请求被阻止 [英] Nodejs SendGrid CORS request blocked

查看:14
本文介绍了NodeJS SendGrid CORS请求被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解Node.js、Reaction等,有以下问题:

我有一个从网页上的表单调用的提交函数,如下所示(出于隐私目的,我省略了一些细节):

class Email extends React.Component{

constructor(props){
    super(props);

    this.state = {
        subject: "",
        message: ""
    };

}

handleUpdateSubjectLine(evt){
    this.setState({ subject: evt.target.value});
}

handleUpdateMessageBox(evt){

    this.setState({ message: evt.target.value});
}


async handle_email(evt){


    var sgMail = require('@sendgrid/mail');
    var subject = this.state.subject;
    var message = this.state.message;
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    console.log("subject txt: " + subject);
    console.log("msg txt: " + message);
    var msg = {
       to: 'OMMITED',
       from: 'OMMITED',
       subject: subject,
       text: message,
    };

    sgMail.send(msg).catch(err =>{
        console.log(err);
    });
    console.log("Message Allegedly Sent!");

}

在我的收件箱中查看由上述表单生成的测试电子邮件时,我不仅看不到任何电子邮件,Web浏览器还会显示以下消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.sendgrid.com/v3/mail/send. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://sendgrid.api-docs.io’).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.sendgrid.com/v3/mail/send. (Reason: CORS request did not succeed).

我已从npm安装了cors@sendgrid/mail,但似乎想不出如何将上面的内容应用于此API调用,尽管我看到其他人在YouTube上实现它。

谢谢!

推荐答案

不允许直接从浏览器前端(Reaction)应用程序发送。(CORS将阻止该请求。)您需要创建一个Node.js服务器(我使用Next JS)并处理从您的服务器发送电子邮件(通过SendGrid API)。以下是关于如何处理这一问题的两个非常好的教程:

使用SendGrid:

https://docs-git-success-185-add-nextjs-sengrid-guide.zeit.now.sh/guides/deploying-nextjs-nodejs-and-sendgrid-with-zeit-now

使用Nodemailer:

https://medium.com/the-couch/adding-a-contact-form-to-your-next-js-app-7a1b5f63f27

这篇关于NodeJS SendGrid CORS请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆