Access-Control-Allow-Origin Error when trying to add open graph meta tags dynamically via Firebase functions

本秂侑毒 提交于 2019-12-25 04:01:17

问题


I'm trying to add open graph meta tags dynamically to my index.html using firebase functions. I'm following this tutorial but because I'd like to allow users to share on their facebook I need to add open graph meta tags on-demand when user wants to share content.

So, it seems to me that running the function via rewrite in firebase.json is not best solution here and I'd like to call the function when user wants to share content to Facebook.

I try to use CORS but it seems I get the "Access-Control-Allow-Origin" error in the browser when I am sending my response back. If I redirect I have no issue. But I need to send the index.html that's been updated. How can I resolve this issue?

Here's my function:

const cors = require('cors')({ origin: true });
const fs = require('fs');
exports.handler = function(req, res) {
    cors(req, res, () => {
    let indexHTML = fs.readFileSync('./hosting/index.html').toString();
    console.log(`@share-fb-formfeed inside cors`, indexHTML);
    const ogPlaceholder = '<meta name="functions-insert-dynamic-og">';
    res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
    res.status(200).send(indexHTML);    //results in Access-Control-Allow-Origin
    // res.redirect(`https://thekasis.com/feed`); //this works  
    });
}

Using Rewrites

I also removed cors in my function and here is my firebase.json but I'm not sure if running the Firebase function all the time would be a good idea. It would be ideal to run the function only on-demand when the user is sharing something and so I really like to be able to call the function client side on-demand.

{
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "build/es5-bundled",
    "rewrites": [{
    "source": "**",
    "function": "shareContentG-shareToFb"    
  }]
  }
}

来源:https://stackoverflow.com/questions/49998010/access-control-allow-origin-error-when-trying-to-add-open-graph-meta-tags-dynami

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!