简体   繁体   中英

Vanilla Javascript API call to randommer.io

I am new to Javascript and I am trying to make an API call to randommer.io using Vanilla Javascript, but it not working. I have read the documentation on Randommer but nothing same to work. I keep getting the Cross-Origin Request Blocked error. Any help how to solve this problem. Below is the code I am using to make the API call and and X-Api-Key is also valid.

 window.addEventListener('DOMContentLoaded', function () { getData() }) const getData = async function() { const result = await fetch(`https://randommer.io/api/Phone/Countries`, { method: 'GET', headers: { "Access-Control-Allow-Origin": '*', Accept: 'application/json', 'x-Api-Key': 'xxxxxx', } }) const data = await result.json() console.log(data) }

You could try using the cors-anywhere proxy which you could also setup yourself.

window.addEventListener('DOMContentLoaded', function () {
getData()
})



const getData = async function() {
    const result = await fetch(`https://cors-anywhere.herokuapp.com/https://randommer.io/api/Phone/Countries`, {
        method: 'GET',
        headers: {
        "Access-Control-Allow-Origin": '*',
        Accept: 'application/json',
        'x-Api-Key': 'XXXX',
        }
    })
    const data = await result.json()
    console.log(data)
}

https://github.com/Rob--W/cors-anywhere

This is happening because you really should be running this server side via something like Node.js since they don't allow cors but this is a workaround if you want to run it like you are.

Your server must accept cors, otherwise this call will not work. What you can do is create a proxy as suggested to bypass its restriction.

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