CORS Error using Appwrite Functions (Using JS clientside)

81 Views Asked by At

I am trying to send a post request to one of my functions and I always get an CORS Error

<script>
  const url = "https://sample.appwrite.global/";
  const headers = {
    "Content-Type": "application/json"
  };

  const data = {
    "key": "",
    "uid": ""
  };

  fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
  })
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

</script>

This is the code on the client side

I have attached the error screenshot as well as platform web app hostname

Any help would be much appreciated Error Screenshot

enter image description here

1

There are 1 best solutions below

0
Sau1707 On

I just had the same problem,
Apparently Appwrite don't set automatically the header in the function response, maybe it's a bug

You are missing "Access-Control-Allow-Origin", in your Appwrite function to add it

export default async ({ req, res, log, error }) => {
    res.send('I am alive!', 200, { "Access-Control-Allow-Origin": "*" });
})

And since this is horrible, I suggest

const addHeaders = (res) => {
    let obj = {}
    obj.send = (body, statusCode = 200, headers = {}) => {
        headers["Access-Control-Allow-Origin"] = "*";
        return res.send(body, statusCode, headers);
    }
    obj.json = (body, statusCode = 200, headers = {}) => {
        headers["Access-Control-Allow-Origin"] = "*";
        return res.json(body, statusCode, headers);
    }
    obj.empty = (statusCode = 204, headers = {}) => {
        headers["Access-Control-Allow-Origin"] = "*";
        return res.empty(statusCode, headers);
    }
    obj.redirect = (url, statusCode = 301, headers = {}) => {
        headers["Access-Control-Allow-Origin"] = "*";
        return res.redirect(url, statusCode, headers);
    }
    return obj;
}
export default async ({ req, res, log, error }) => {
     res = addHeaders(res)
    res.send('I am alive!')
});

References: