Tuesday 18 April 2023

JavaScript fetch, VS Code, CORS, Debugging and curl

I've recently been trying to use the Pocket API to bring my favourite links into a page. Naturally, I was starting from a position of testing it on localhost. I've also been using VS Codium, which has improved on Ubuntu. I use the Brave browser and so was looking to make use of this in my debugging.

So first things, first I needed to get debugging happening in VS Codium using Brave on Ubuntu. As you try and run the debugger, you have the option to create a launch.json file for your project. Here, I selected to create a Chrome web app. Once the launch.json was created, I edited it with the following, in order that the debugger used Brave:

{

    "version": "0.2.0",

    "configurations": [

        {

            "type": "chrome",

            "request": "launch",

            "name": "Brave",

            "runtimeExecutable": "/opt/brave.com/brave/brave-browser",

            "userDataDir": true,

            "url": "http://localhost:5500",

            "webRoot": "${workspaceFolder}",

            "runtimeArgs": ["--disable-web-security"]

        }

    ]

}

I the setting "--disable-web-security" fixed the CORS problem commonly faced such as,

Access to fetch at ‘http://localhost:8000/api/v1/messages’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The final issue I encountered was the code itself. I'd successfully retrieved the data I was looking for using curl, but converting the curl command to a JavaScript fetch was problematic. I then came across this page which helped.

Now we're cooking!