0

I am working on a chrome extension that creates an Anki card and adds it to my desk. Right now am I trying to get the request to work using the Anki API. For some reason the server is denying my request.

Here is my code (JavaScript) to create a card and send it as a request to the localhost:

async function createCard() {
  // Set the Anki API endpoint URL
  const baseURL = 'http://localhost:8765';

  // Set the Anki API action, version and params
  const card = {
    "action": "addNote",
    "version": 6,
    "params": {
      "note": {
        "deckName": "Default",
        "modelName": "Basic",
        "fields": {
          "Front": "front content",
          "Back": "back content"
        },
        "options": {
          "allowDuplicate": false,
          "duplicateScope": "deck",
          "duplicateScopeOptions": {
            "deckName": "Default",
            "checkChildren": false,
            "checkAllModels": false
          }
        }
      }
    }
  };

  // Send the request to the Anki API
  try {
    const response = await fetch(baseURL, {
      method: 'POST',
      mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(card)
    });

    // Check the status code of the response
    if (response.ok) {
      console.log('Card created successfully');
    } else {
      console.error(`Error creating card: ${response.statusText}`);
    }
  } catch (error) {
    console.error(`Error creating card: ${error}`);
  }
}

(The card by now is hardcoded.)

When I execute this code I get 2 errors thrown by chrome:

  1. POST http://localhost:8765/ net::ERR_ABORTED 403 (Forbidden)
  2. Error creating card:

The first error happens on the fetch function and the second error at "console.error('Error creating card: ${response.statusText}');"

I suggest that the second error appears due to the first one.

Since I am new to computer science, all I tried so far is checking the logs of ANKI to find information about the error, but I couldn't find something. I tried different syntax to create the card since I pass this into the fetch function where the error occurs.

The localhost is running while I am working on this, so the server is accessible.

jthulhu
  • 7,223
  • 2
  • 16
  • 33
  • Add `http://localhost/` to host_permissions in manifest.json and don't make the request in the content script ([more info](https://stackoverflow.com/a/55292071)). – wOxxOm Dec 31 '22 at 15:50

1 Answers1

0

My solution is setting the webCorsOriginList config of AnkiConnect as "*"

"webCorsOriginList": ["*"]

It will allow CORS for all domains.