-1

Im trying to use an API for my website. I am trying to send a POST request with JSON data. But when I try to send the request I get an error code. I have tried sending the request with curl and that works without any problem.

Access to XMLHttpRequest at 'https://mpc.getswish.net/qrg-swish/api/v1/prefilled' from origin 'http://192.168.0.90' 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.

Curl command

curl --data '{"format":"svg","size":300,"message":{"value":"test","editable":true},"amount":{"value":100,"editable":false},"transparent":true}' --header "Content-Type: application/json" --output output.png --request POST https://mpc.getswish.net/qrg-swish/api/v1/prefilled

I have enabled Access-Control-Allow-Origin in apache configuration.

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName web
        ServerAlias web
        DocumentRoot /var/www/web
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        Header always set Access-Control-Allow-Origin "*"
        Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
        Header always set Access-Control-Allow-Methods "GET,POST,PUT,OPTIONS"
</VirtualHost>

And this is my jQuery code

$.ajax({
    type: 'POST',
    url: 'https://mpc.getswish.net/qrg-swish/api/v1/prefilled',
    data: '{"format":"svg","size":300,"message":{"value":"test","editable":true},"amount":{"value":100,"editable":false},"transparent":true}',
    headers: {  'Access-Control-Allow-Origin': '*' },
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

Thanks!

Skolmen
  • 11
  • 3

1 Answers1

2

If you are using an API that enforces CORS, then it probably means they don't want you to call it from a web browser at all. What you need to do is make your own back-end which your front-end will talk to. So your AJAX call needs to go to your own back-end, which calls the API, and sends the result back. The back-end can call the API without CORS limits. Only web browsers enforce CORS for security measures.

chrispytoes
  • 1,714
  • 1
  • 20
  • 53