How to properly make requests to remote websites from a plugin? I tried simple
fetch("URL"), but it is blocked by CORS:
Access to fetch at 'https://url' from origin 'app://obsidian.md' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My personal fave way to work around CORS issues is to create a middleware server that you control. From there, you can make whatever external calls you want. Then from your plugin
fetch($YOUR_SERVER) because you control both ends you can set the correct CORS policy.
A super simple (and free) way to do this is using Glitch’s express server template. Add the
cors npm package and use it with express:
app.use(cors()). You’ll be able to fetch any endpoint you setup in
express within your plugin.
There are other ways and some are faster/easier, but controlling both sides of the request is the best way imho.
Obsidian is an electron app which means it is essentially Chrome under the hood. You’ll need to handle CORS like you would in any other client-side cross domain request just as the error indicates.
You could try throwing
no-cors on the fetch request. Or Google handling cors with fetch.
If you want to go the quick-n-dirty route lookup ‘cors anywhere’. I wouldn’t ship a plugin with cors anywhere though as it’s liable to break.
Setting up a server of Glitch is pretty fast and easy tbh. Just use the express template and move your cross-browser fetching into the glitch app.
fs module for local files. I thought that something similar is available for web requests.
If you are okay with your plugin only working in the desktop you can use the package node-fetch. GitHub - node-fetch/node-fetch: A light-weight module that brings the Fetch API to Node.js node’s libraries bypass cors restrictions but are only available in the desktop apps.
I have a similar problem. I want to implement a CalDav Client Plugin and get the same error.
I try to implement a middleware with express and the cores package, but it doesn’t work. Can someone give me please a code example, a tutorial or a link to the Glichßs express server?