express CORS sometimes allow, some times does not

  ajax, cors, express, javascript, node.js

I have a Node.js app using Express.

Here are the CORS custom options:

const corsOpts = {
  origin: [
    '... some domains'
  ],

  methods: ['GET', 'POST'],
  credentials: true,

  allowedHeaders: ['Content-Type', 'authToken'],
};
app.use(cors(corsOpts));

Here’s the code that makes the $.AJAX calls:

//This one goes just fine    
await $.ajax({
                async: true,
                crossDomain: true,
                url: 'https://domain/cscJuridico/submitSing',
                method: 'POST',
                headers: {
                  'content-type': 'application/json',
                },
                data: JSON.stringify({
                  name: response,
                  data: signaturePad
                    .toDataURL('image/png')
                    .replace(/^data:image/(png|jpg);base64,/, ''),
                }),
              });
    
              for (var i = 0; i < cedulasData.length; i++) {
                console.log('UPLOADING CEDULA: ' + i);
                //only the first one goes trough, the other ones get a CORS error
                await new Promise(async function (res, rej) {
                  setTimeout(async function () {
                    await $.ajax({
                      async: true,
                      crossDomain: true,
                      url: 'https://domain/cscJuridico/submitSing',
                      method: 'POST',
                      headers: {
                        'content-type': 'application/json',
                      },
                      data: JSON.stringify({
                        name: response + ' - ' + i,
                        data: cedulasData[i],
                      }),
                    });
                    res(null)
                  }, 2000);
                });
              }

I also tried this for the path:

app.use('/cscJuridico/submitSing', cors({
  origin: "*",
}))

Here’s how that POST path looks like:

app.post('/cscJuridico/submitSing', (req, res) => {
  var data = req.body;
  var name = data.name;
  var imageData = data.data
    .replace('data:image/jpeg;base64,', '')
    .replace('data:image/png;base64,', '');

  fs.writeFileSync(
    patch.resolve(`./public/images/${name}.png`),
    imageData,
    'base64'
  );
  res.send();
});

How is it possible that the same request sometimes goes well and sometimes get CORS error? What am I missing?

The exact CORS error I’m getting:

Access to XMLHttpRequest at 'https://acq.mejiatavarez.com/cscJuridico/submitSing' from origin 'https://agentedecambioquezada.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Source: Ask Javascript Questions

LEAVE A COMMENT