-1

there is an external REST API which is used for uploading resources to a repository. I can use it using curl command:

curl -k -X POST -u username:password \
-F package_id="1234" \
-F file=@"path_to_a_file" \
https://url_api_prefix

I want to implement a UI, so users can upload files by simply selecting a file and click submit. So I have written some HTML:

<form id="my-form" method="POST" enctype="multipart/form-data" action="https://url_api_prefix">
    <input type="text" name="package_id">
    <input type="file" name="file">
    <button type="submit">Submit</button>
</form>

This works fine, but it will redirect me to a new page showing some JSON data returned by the server. I don't want this showing in a redirected page; I want is on an alert box or something like that popping up on current page. So I followed answers here How to submit html form without redirection? and wrote this in javascript:

$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
    url:$(this).attr('action'),
    type:'post',
    data:$(this).serialize(),
    success:function(data){
        alert('success ' + data.message);
    },
    error:function(jqXHR, textStatus, errorThrown) {
        alert(textStatus + ': Unable to post. HTTP status: ' + errorThrown);
    }
});

But now when I click submit, it will give me CORS error:

Access to XMLHttpRequest has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have read some article about CORS error, and it seems that if it's an external API, there's nothing client side can do. Why using this API in js gives me CORS error, but HTML itself works fine? Is there any way I can fix this CORS error on client side?

alsjinus
  • 77
  • 1
  • 10
  • Only way to manage it client side is through a third party proxy service or set up a proxy on server you control – charlietfl Jun 28 '20 at 04:58

1 Answers1

2

CORS is something managed by the browsers to make things secure in JavaScript XMLHttpRequest operations between different domain addresses. It works with HTML form post; because when you submit the form, your browser actually redirects to that domain, the page address changes.. But with ajax, you're still staying on your own web page.

There are several solutions to this :

  1. If the second web site is also managed by you, you should add "Access-Control-Allow-Origin" to response headers from that second web site. When you make an async http operation in JavaScript (such as ajax here) to a different domain address; browser first makes a dummy "HTTP OPTIONS" request to that target address to check if this header is present.. If it finds this header in response, it know it's allowed and it makes your actual request. Otherwise, it blocks your request and gives the error you encountered.

    Access-Control-Allow-Origin: https://the-site-making-the-request.com
    
  2. You can make a custom fake proxy page on your web site; and on server side you can fetch the content from second web site with CURL or other http client tools specific to your server side language. And then send back same response;

    $.ajax({
          url:"https://my-own-website.com/webproxy.php?url=https://other-website.com/something",
           ....
           ....
    
  3. If your application is user/company specific like only will be accessed on local network; you can disable CORS on browsers advanced security settings. But it is highly dangerous and not recommended.

Noldor
  • 1,122
  • 9
  • 22
  • 1
    Thanks for your answer! For option 2 do you mind to provide more details? Do you mean I can write another API on my server side which make a http post request to that external API and get the response? – alsjinus Jun 28 '20 at 06:34
  • 1
    @alsjinus Yes. You need to make a separate server side page/api, and make the http post job from your server side to that other api.. use the same post parameters from your ajax, pass same parameters to other api, and then get the response from that other api and return it as it is.. that way, your url will be on your website in javascript and you won't have CORS errors on browsers. Depending on your server-side language, probably there is already some ready-to-use proxy sample codes out there which are mapping everything you post to target url.. – Noldor Jun 28 '20 at 07:08