无法在使用 CORS 和 Mandrill 的 Node Express 中找出“没有'访问控制-允许源'

Can't figure out "No 'Access-Control-Allow-Origin' header" in Node Express with CORS and Mandrill

本文关键字:没有 许源 访问控制 CORS Express Node Mandrill      更新时间:2023-09-26

我已经阅读了足够多的内容,知道我对这个迷失了方向。其他线程上的解决方案似乎没有帮助。

我在pages.samedomain.com 有一个页面,在我的Node站点apps.samedomain.com 调用mandrill api。使用 ORM,我能够很好地编写表路由。写入表并且页面收到确认后,它应该触发到电子邮件路由。在本地运行时,两者都可以正常工作。部署时,我得到...

XMLHttpRequest 无法加载 http://apps.samedomain.com/.../.../mail/4847775376401843。请求的资源上不存在"访问控制允许源"标头。因此,不允许访问源"http://pages.samedomain.com"。响应具有 HTTP 状态代码 502。

在我的应用程序中.js我有...

var cors = require('cors');
app.use(cors());

在我的路由文件中,我有...

module.exports = function(appRouter) {    
var mandrill = require('mandrill-api/mandrill');
var mandrill_client = new mandrill.Mandrill(process.env.MANDRILL_API_KEY);    
appRouter.route('/.../mail/:first_list_id').post(function(req,res){
    req.models.know_me_2016
        .find({list_id:req.params.first_list_id})
        .run(function(err, results){
            if (err) { 
                res.send(err); 
            } else {
                var template_content = [{
                    "recipient": <stuff> ,
                    "content": <stuff>
                }];
                var message = {
                    <mandrill message object stuff>
                };
            }
            mandrill_client.messages.sendTemplate({
                "template_name": <template-name>, 
                "template_content": template_content, 
                "message": message}, function(result) {
                    console.log(result);
                    //I tried adding header stuff but it didn't help, maybe in wrong place? I thought CORS library was going to take care of this part?
                    res.header("Access-Control-Allow-Origin", "http://interactives.dallasnews.com");
                    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    //It sends successfully when run local
                    res.send("Email sent successfully");
                }, function(e) {
                    // Mandrill returns the error as an object with name and message keys
                    console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
                    // A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
            });
        });        
    });
}

我的山钻密钥设置为接受所有 IP。

任何见解将不胜感激。

初始化 cors 时,您需要将允许的源添加到白名单中:

var whitelist = [
    'http://samedomain.com',
    'http://apps.samedomain.com',
    'http://pages.samedomain.com'
    // list whatever possible domains you have
]
var globalCorsOptions = {
    origin: function(origin, callback) {             
        callback(null, whitelist.indexOf(origin) !== -1);
    }
};
var cors = require('cors');
app.use(cors(globalCorsOptions));

在这种特殊情况下,事实证明问题在于缺少更新的.env文件。我们的私有 git 会忽略 .env 文件,因此不会发布凭据。山魈无法连接。插入 Mandrill 凭据并更新 .env 遥控器后,它开始按预期工作。