I am trying to call a Freesound API. Fetch throws an Unauthorised error whereas Postman works.
Code
const BASE_URL = "https://freesound.org/apiv2/sounds/";
const rain = "58835";
const APIKEY = "foo";
const headers = {
method: "GET",
headers: {
'Authorization': `Token ${APIKEY}`,
},
mode: "no-cors",
};
fetch(BASE_URL + rain, headers)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));
First of all, you should never post API Key on any public platform as anyone can access and exploit the API that you would have paid for.
Solution
The endpoint you're using seems to be invalid. Also, don't use mode: 'no-cors' unless an opaque request serves your need. Else, you won't be able to access any property in the response object.
Reason of 401 error: Using no-cors prevents Authorization header to be added in your request.
Getting past CORS error: It usually happens in localhost during development. You can use an extension which would allow CORS.
const QUERY = 'piano';
const API_KEY = 'foo';
const BASE_URL = `https://freesound.org/apiv2/search/text/?query=${QUERY}`
const headers = {
method: 'GET',
headers: {
Authorization: `Token ${API_KEY}`,
}
};
fetch(BASE_URL, headers)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));
Related
Managed to get a JSON response in Postman, but got an empty response in the console, with no errors whatsoever.
here's the code:
function getFetch() {
const url = `https://fantasy.premierleague.com/api/bootstrap-static/`;
let requestOptions = {
method: "GET",
redirect: "follow",
mode: 'no-cors',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "x-requested-with"
};
fetch(
"https://fantasy.premierleague.com/api/bootstrap-static/",
requestOptions
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
}
P.S: I also get the JSON if I typed the URL in the browser. But not with a fetch
Assuming you are trying that in browser, client-side:
Cross-origin mode: 'no-cors' requests have no access to response body and headers, basically they blindly send data but cannot see the result.
Those Access-Control-… headers are not for the request, but for the server response. If the server responded with them, the response would be readable from all origins. (Provided such requests were not self-restrained by mode: no-cors as describer above.)
You can see that no mater what you fetch, response is always with status: 0 and ok: false:
function runFetch() {
console.clear();
fetch(
url.value, {
mode: nocors.checked ? 'no-cors' : 'cors'
},
)
.then((response) => {
console.log('Response status:', response.status, ', OK:', response.ok);
return response.text()
})
.then((result) => console.log("Result: »" + result + "«"))
.catch((error) => console.log("error", error.message));
}
runFetch()
<label>URL: <input id="url" value="https://fantasy.premierleague.com/api/bootstrap-static/" /></label>
<br><label>no-cors: <input type="checkbox" id="nocors" checked /></label>
<br><button onclick="runFetch()">run</button>
I need some help in re-formatting the JS script to Zoho Deluge script.
This API sends whatsapp template message.
I was able to parse headers but not custom parameters.
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json-patch+json',
Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ZDE1YTlkNi05MDQ2LTQ3OGMtYTk1MS0zNTA0ZDFlMGVkOGEiLCJ1bmlxdWVfbmFtZSI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwibmFtZWlkIjoidmlsYWtzaGFuQG5pdmVzaG9ubGluZS5jb20iLCJlbWFpbCI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwiYXV0aF90aW1lIjoiMDIvMjEvMjAyMiAxNjo0MjozOSIsImRiX25hbWUiOiI3MzU0IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQURNSU5JU1RSQVRPUiIsImV4cCI6MjUzNDAyMzAwODAwLCJpc3MiOiJDbGFyZV9BSSIsImF1ZCI6IkNsYXJlX0FJIn0.f1eGyiKdnj9xj48e8WUnLzTD6UGmztJGu7HrKH886og'
},
body: '{"receivers":[{"customParams":[{"name":"1","value":"Missed"},{"name":"2","value":"IVR"},{"name":"3","value":"09910076952"},{"name":"4","value":"MFP1320"},{}],"whatsappNumber":"919910076952"}],"template_name":"ivr_lead","broadcast_name":"sample"}'
};
fetch('https://live-server-7354.wati.io/api/v1/sendTemplateMessages', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
According to your questions, you want to do POST URL using deluge script.
Based on your current data, the script to call post url is here;
url_post = "https://live-server-7354.wati.io/api/v1/sendTemplateMessages";
content_type = "application/json-patch+json";
authorization = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ZDE1YTlkNi05MDQ2LTQ3OGMtYTk1MS0zNTA0ZDFlMGVkOGEiLCJ1bmlxdWVfbmFtZSI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwibmFtZWlkIjoidmlsYWtzaGFuQG5pdmVzaG9ubGluZS5jb20iLCJlbWFpbCI6InZpbGFrc2hhbkBuaXZlc2hvbmxpbmUuY29tIiwiYXV0aF90aW1lIjoiMDIvMjEvMjAyMiAxNjo0MjozOSIsImRiX25hbWUiOiI3MzU0IiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQURNSU5JU1RSQVRPUiIsImV4cCI6MjUzNDAyMzAwODAwLCJpc3MiOiJDbGFyZV9BSSIsImF1ZCI6IkNsYXJlX0FJIn0.f1eGyiKdnj9xj48e8WUnLzTD6UGmztJGu7HrKH886og";
parameters_value = '{"receivers":[{"customParams":[{"name":"1","value":"Missed"},{"name":"2","value":"IVR"},{"name":"3","value":"09910076952"},{"name":"4","value":"MFP1320"},{}],"whatsappNumber":"919910076952"}],"template_name":"ivr_lead","broadcast_name":"sample"}';
parameters_value_map = parameters_value.toJSONList().toMap();
headers_value = Map();
headers_value.put("Content-Type",content_type);
headers_value.put("Authorization",authorization);
response_data = invokeUrl
[
url: url_post
type: POST
headers: headers_value
parameters:parameters_value_map
];
info response_data;
Please refer to this article for much details https://www.zoho.com/deluge/help/webhook/invokeurl-api-task.html
Thanks,
Von
Hi i want to fetch data from avascan api and display it in html, but i am not able to do this. I have tried fetch api, json and ajax ways but none worked for me. Any suggestions? This is my html https://avascan.info/api/v1/home/statistics
const api_url = 'https://avascan.info/api/v1/home/statistics';
async function getAVA() {
const response = await fetch(api_url);
const data = await response.json();
const {
blockchains,
validators
} = data;
document.getElementById('lat').textContent = blockchains.toFixed(2);
document.getElementById('lon').textContent = validators.toFixed(2);
}
getAVA();
setInterval(getAVA, 1000);
<h1>What the stats?</h1>
<p>
blockchains: <span id="lat"></span>°<br /> validators: <span id="lon"></span>°
</p>
<div id="issMap"></div>
You are getting a CORS protection error, as mentioned before.
However it seems you need to use a GraphQL API: https://graphql.avascan.info/
Look at this quick example:
async function getAVA() {
fetch('https://graphql.avascan.info', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query {
stats {
priceAvaxUsd,
connectedNodes
}
}`
}),
})
.then((res) => res.json())
.then((result) => console.log(result));
}
getAVA();
Looks like you have this error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is a CORS protection and you may need certain requirements to fetch this dat such an api key, or update configuration your options in the fetch method
Here is a resource to help
I am trying to access the Bing Custom Search API. Custom Search Instance is setup and able to call API from BING portal (production tab), however when I am trying to access the same URL through JS. I am getting Failed Request as below
Below is the way I am accessing the API:
const query = "app";
const url = `https://api.bing.microsoft.com/v7.0/custom/search?q=${query}&customconfig=<CUSTOM_CONFIG_ID>&mkt=zh-CN`;
const option = {
mode: "cors",
headers: {
"Ocp-Apim-Subscription-Key": <Subsription Key>
}
};
fetch(url, option)
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err));
I am getting error
TypeError: Failed to fetch
Find CUSTOM_CONFIG_ID in https://www.customsearch.ai/ .
Find Ocp-Apim-Subscription-Key on portal.
const fetch = require("node-fetch");
const query = "app";
const url = `https://api.bing.microsoft.com/v7.0/custom/search?q=${query}&customconfig=<CUSTOM_CONFIG_ID>&mkt=zh-CN`;
const option = {
mode: "cors",
headers: {
"Ocp-Apim-Subscription-Key": '<Subsription Key>'
}
};
fetch(url, option)
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log("err: " + err));
My Test Result:
Please run node install node-fetch first.
This question already has answers here:
How to send authorization header with axios
(12 answers)
Closed 4 years ago.
I'm new to Vue.js and want to make a request in a component to a restricted api:
computed: {
token () {
return this.$store.getters.getToken;
},
...
created () {
axios
.get( this.BASE_URL + '/profile/me')
.then( res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))
},
The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.
And when I try
axios.defaults.headers.common['Authorization'] = this.token;
before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.
How can I fix it?
Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.
axios.get(yourURL, yourConfig)
.then(...)
In your case yourConfig might be something like this
yourConfig = {
headers: {
Authorization: "Bearer " + yourJWTToken
}
}
Also you can read about what you can put in your config here https://github.com/axios/axios.
Just search for "Request Config"
This works for me, try like -
let JWTToken = 'xxyyzz';
axios
.get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })
.then(res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))