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.
Related
i sent a request to the mongodb to get some data according to email.my client side code is working
properly .
code is here:
useEffect(()=>{
const email = user?.email;
// console.log(email)
const url = `http://localhost:5000/services?email=${email}`;
console.log(url)
fetch(url)
.then(res => res.json())
.then(data => setItems(data))
},[user])
console.log showing the data as i expected
but the problem start with the backend. i tried console.log to get the email and other thing but the code is not showing nothing even not a single error.
here is the code i wrote for api with express:
app.get('/services',async(req,res)=>{
const email = req.query.email;
console.log(email)
const query = {email:email};
const cursor = serviceCollection.find(query);
const item = await cursor.toArray();
res.send(item);
});
So far I didn't see any issue with your code.
Have you tried to call your GET request from the browser directly?
You might check on req and res to see the incoming data to that endpoint (/services)
You also can try to add the request options in your fetch method
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
const email = user?.email;
const url = `http://localhost:5000/services?email=${email}`;
fetch(url , requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
And I suggest you to using Postman, to call that endpoint. It will easier to debug the API using 3rd party app like Postman.
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));
Actually am kinda disappointed as I tried many things and checked out many articles but non worked out for me.
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://***********.com/connect/api.php?action=2&token="+tokenV;
const myHeaders = new Headers();
const myRequest = new Request(urlF, {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default',
});
fetch(myRequest)
.then(response => response.json())
.then(data => console.log(data));
}
I have already whitlist the domain inside my config file, am using phonegap CL latest version. I'm trying to connect to an api which will out put json.encode data if token were right.
Error output:
(index):50 Fetch failed loading: GET https://*******.com/connect/api.php.............
Another way I tried using cordova fetch plugin still failed:
function demo() {
console.log("Booooooooooooommmmmmmmmmm");
tokenV = document.getElementById("tokenString").value;
var urlF = "https://*********.com/api.php?action=2&token="+tokenV;
console.log("nowww1");
cordovaFetch(urlF, {
method : 'GET',
headers: {
'User-Agent': 'CordovaFetch 1.0.0'
},
})
.then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
});
}
Error out put:
Error: exec proxy not found for :: FetchPlugin :: fetch (index):118 parsing failed TypeError: Network request failed
I can change the out put as I want but show me away to get the data from an external server???
Thank you
I have a Node Js server, in it, I am fetching a blob data from another web service (which is for a PDF file), now after receiving blob, I want to convert it again into PDF file.
Anyone, who knows how to achieve this please help.
Here is my code block I have tried so far:
const fetch = require('node-fetch');
const Blob = require('fetch-blob');
const fs = require('fs');
fetch(url, options)
.then(res => {
console.log(res);
res.blob().then(async (data) => {
const result = data.stream();
// below line of code saves a blank pdf file
fs.createWriteStream(objectId + '.pdf').write(result);
})
})
.catch(e => {
console.log(e);
});
Modification points:
For fs.createWriteStream(objectId + '.pdf').write(data), please modify res.blob() to res.buffer().
Please modify .then(res => {res.blob().then() to .then(res => res.buffer()).then(.
Modified script:
fetch(url, options)
.then(res => res.buffer())
.then(data => {
fs.createWriteStream(objectId + '.pdf').write(data);
})
.catch(e => {
console.log(e);
});
Note:
In this modification, it supposes that the fetch process using url and options works fine.
References:
node-fetch
write()
I'm trying to get a json file from an api, when using this code on node.js it works perfectly fine and I can see the results I'm looking for, but when I try to use it from the browser it fails and returns with the error message on the title.
async function searchVolumes(volume, url, apiKey) {
let result = await fetch(url, {mode: 'no-cors'})
.then(res => res.json())
.then(json => json.results)
.catch(error => console.log('Error reading data ' + error))
return result
}
I've tried it in Firefox and Edge and have the same problem in both of them, but checking the network tab I can see the result and the json is fine with no errors, and as I say at the beginning it works on node too.
I modified it according to sideshowbarker links and removed the no-cors mode and added a proxy cors anywhere server and it's working now:
const proxy = 'https://cors-anywhere.herokuapp.com/'
url += proxy
async function searchVolumes(volume, url, apiKey) {
let result = await fetch(url)
.then(res => res.json())
.then(json => json.results)
.catch(error => console.log('Error reading data ' + error))
return result
}