1

I have been banging my head against the wall for hours now... tried every type of combination to get this working.

I have my own API endpoint here: https://app.automate.mn/api/tools/email/add

Which I am trying to post data to from 3rd party websites.

app.js

const express = require('express');
const cors = require('cors');
const app = express();
    
app.use(cors());
app.options('*', cors());

...
    
const {addContact} = require('./routes/api/tools/email');
app.post('/api/tools/email/add', addContact);

addContact.js

addContact: async function (req, res) {

    res.status(200).send('OK - TEST');
    return;
}

I have setup a test website here with the form: https://demoautomatemn.wpcomstaging.com/

When you submit the form, it's posting the data to the endpoint:

loadForm.js

automate_post_data('https://app.automate.mn/api/tools/email/add', data)
            .then(data => {
                console.log(data); // JSON data parsed by `data.json()` call
            });

async function automate_post_data(url = '', data = {}) {
const response = await fetch(url, {
    method: 'POST',
    mode: 'cors', // no-cors, *cors, same-origin
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    //referrerPolicy: 'origin', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
});

if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);
}
return response.json();
}

The post is failing:

Access to fetch at 'https://app.automate.mn/api/tools/email/add' from origin 'https://demoautomatemn.wpcomstaging.com' 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.
loadForm.js:109 POST https://app.automate.mn/api/tools/email/add net::ERR_FAILED

enter image description here

enter image description here

I was expecting to see the "Access-Control-Allow-Origin" in the response headers for the OPTION call but nothing (Preflight response is not successful). I have tried everything to get it working.

Any suggestions would be so welcome right now.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Andy
  • 59
  • 2
  • 11

1 Answers1

0

OK, Progress but no cigar!

I setup the following:

Setting at apache level:

https://docs.bitnami.com/bch/infrastructure/nodejs/administration/enable-cors-nodejs/

You might also find this helpful: https://enable-cors.org/server_apache.html

Adding origin to the request

 headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Origin': window.location.href
    },
referrerPolicy: 'origin',

This then resulted in the error message changing:

Access to fetch at 'https://app.automate.mn/api/tools/email/add' from origin 'https://demoautomatemn.wpcomstaging.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Update 'Content-Type': 'application/x-www-form-urlencoded',

As per this post: Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

I updated the request to x-www-form-urlencoded

const response = await fetch(url, {
        method: method,
        mode: 'cors', // no-cors, *cors, same-origin
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': window.location.href
        },
        referrerPolicy: 'origin', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: data // body data type must match "Content-Type" header
    });

It feels like progress however I am still getting 406 error:

POST https://app.automate.mn/api/tools/email/add 406

Response {type: "cors", url: "https://app.automate.mn/api/tools/email/add", redirected: false, status: 406, ok: false, …}
Andy
  • 59
  • 2
  • 11
  • Added in the following header and it seems to be working 'Accept': 'application/x-www-form-urlencoded', – Andy Jul 01 '20 at 11:06