简体   繁体   中英

How to make API request javascript code with using api_key?

I made API request in Python.

import requests

key = 'my key'

params = {
  "file1" : 'file'
}

headers = {
  "Authorization" : "Bearer {}".format(key)
}

r = requests.get('url', params=params, headers=headers)

json_response = r.content.decode("utf-8", "ignore")
writeFile =open('samples.json', 'w')
writeFile.write(json_response)
writeFile.close()
print(r.json())

I want to make API request in javascript using ajax,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
    var key = 'my key';
    $.ajax({
        type : 'GET',
        url : 'url',
        headers: {'Authorization': "Bearer "+ (key)},
        data : {"file1" : 'files'}
        ,success : function(result){
            console.log(result);
        }
    })

})
</script>

But it doesn't work with this error.

Access to XMLHttpRequest at 'url?file1=files' from origin ' http://127.0.0.1:5500 ' 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.

And the server returns this status

"OPTIONS url?file1=file HTTP/1.1" 200 -

What should I do?

You can do this way, take out your key and header code and see if the same message persists, if it does, you might be aware that this problem should be solved on the applications backend (server-side), by managing cors access, if you don't have backend access, try using an extesion to mozzila's browser (firefox), called 'CORS Everywhere', turn it on and try again but keep mind that is just a temporary manner to solve this. Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM