Plugin won't connect to API

Hello!
I am trying to hookup a plugin to an API.

Basically, I am extracting the local variables from a Figma file and I want to store them in a database. Thus far, I am able to get the variables to my codebase.

I have also built a simple API that adds a row to my database. I know that the API works because I have tested it in Postman and get the expected response.

The function to use this API call in the code looks like this:

async function sendJSONToDB(files) {
  console.log("in download"); // this prints, so I know I have entered the function
  const response = await fetch('http://localhost:3000/api/v1/addColorsRecord', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    mode: 'no-cors', // new line
    body: JSON.stringify({
      json_data: files.json_data
    })
  });
  console.log("past fetch") // this does not print, so I never get past the fetch call
  const data = await response.json();

  console.log(data);
 }

Where “files” is an object that looks like this:

let files = {
      json_data: "{}",
      type: "DOWNLOAD"
}

The API function I am calling looks like this:

//POST Method
const addColorsRecord = async (req, res, next) => {
        let conn;
        console.log("in addColorsRecord") // this does not print, so I don't even enter this function
  try {
	conn = await pool.getConnection();
	await conn.query("INSERT INTO COLOR value (?, ?, ?)", [null, req.query.json_data, getCurrentDateTime()]);
    console.log("something has happened")
        const newColorEntry = {
            json_data: req.query.json_data,
            created_on: getCurrentDateTime(),
        };
        res.json(newColorEntry);
    } catch (e) {
        next(e);
    }
};

router.route("/api/v1/addColorsRecord").post(addColorsRecord);

So, any help to figure out why the fetch call is not going through would be much appreciated!
Thanks!

What error are you getting? Did you set up CORS on the server to allow access from any origin (which is null in the plugin)?

Hi @Gleb that’s part of the weird thing… there is no error… it just seems to exit…

That being said, per your other point, I was getting the classic CORS error:

Access to fetch at 'http://localhost:3000/api/v1/addColorsRecord' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

But I added in the lines:

    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    mode: 'no-cors', // new line

But now it just never makes it.

1 Like

This is not really the solution, at least not for production. You’ll need to change the server code to allow access from all origins like I already mentioned.