0

As you know we can't fetch a url on a client side due to CORS. I am trying to create a function, that will fetch the file for me with the right headers as an agent, and will return it to the client.

So, on Firebase Function :

exports.urlToBlob = functions.https.onRequest((request,response) => {
  cors(request, response, () => {

    var url = "https://..."; //request.query.url;
      fetch (
          url,
          {
             method: 'GET',
             headers: { 'Accept': '*/*' }
          }
       )
       .then ((res) => {console.log(res);return res;})

       .catch((err) => response.status(400).send(err))
   });
});

I can see that it will access the url and get a respond on shell simulator, but not on browser, which will return nothing.

The client suppose to access it with :

  var url = "https://us-central1-myproject-6xxxx.cloudfunctions.net/urlToBlob";
        $.get(
        url,
        {url :imgurl, platform : 'xxx'},
        function(data) {
              console.log(data);
        }
       );

I know i am doing it wrong, but i have to find a way to use the function to solve the CORS.

1 Answer 1

1

Have you tried use cors lib from nodejs. You can make a configuration for cors to allow cors in your instance. First install cors lib:

npm install cors --save

After that you can configure cors in you main module application. As an example:

const cors = require('cors')
//cors config
app.use(cors({
  origin: ['https://example.com'] //<-- Here you put the domain you want to call your api
  methods: "GET, POST, PUT, DELETE",
  optionsSuccessStatus:200,
  credentials: true
}))

In your code:

.then ((res) => {console.log(res);return res;})

You should change to:

 .then ((res) => {
    console.log(res);
    //return res;
    response.status(200).send(res);
 })
Sign up to request clarification or add additional context in comments.

5 Comments

HEY, thanks, i wrote that the CORS works on the server, but i can't pass the res to client for some reason. It is empty.
thanks, so if i use your edited code, and access this function on the browser, i will see: {"size":0,"timeout":0}
You will see what you print in console.log(res), maybe if you need this information you can use console.log(res.body).
thanks, did you see how i access it on the client side with $.get ? please look at my question, you can see there that i print console.log(data); , which show an empty object
Yes, i see. But don't know what you are using for do the request in client side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.