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?