Need help with Bing search API React

Ok so I’m having trouble with this Bing API. I can’t seem to get the ajax call right. I’m using react and superagent

handleTermChange(term) {
const url = http://api.cognitive.microsoft.com/bing/v7.0/search?q=${term.replace(/\s/g, )};
request.get(url)
.set({‘Ocp-Apim-Subscription-Key’: ‘myapikey’})
.then((err, res) => {
this.setState({ searchResults: res.body.data })
});
}

I’ve gone over the documentation here is the link to the azure website: Quickstart: Perform a web search with Node.js - Bing Web Search REST API - Azure AI services | Microsoft Learn
Can anyone help or direct me in the right path? Thanks

I’m wondering why you are using replace with nothing in the second parameter.

Here’s an example:

term = 'hello cats'; // string with 1 space in it
term.replace(/\s/g, ); // replaces all single spaces with undefined --> "helloundefinedcats"

what you probably want is:

term.replace(/\s/g,'%20'); 

hello%20cats (%20 represents spaces in urls)

or

term.replace(/\s+/g,'%20');

if you have multiples spaces in a row and you only want to show it as a single space (term = 'hello cats'; becomes 'hello%20cats')

1 Like

Thanks it was a late night but the second parameter isn’t my biggest concern I did add one though. Right now I can’t figure out why my api key isnt working in React. I’ve tried several variations of code it works in simple js as a node application but I can’t seem to make it work with React.

What kind of errors are you getting ?

This is the error I keep getting

Preflight is the first request/response when dealing with cors. The server is suppose set headers for initializing the request and response conversation it’s about to have. The bing API is probably not understanding your initial request or it’s not hitting the right target.

Two questions:
Do you know how to check your XHR headers using the browser Dev Tools?

And is superagent a requirement for this project? JavaScript comes with a few XHR options, one being the Fetch API which I like a lot and is much simpler, IMO.

Yes I know how to check the XHR headers using the dev tools and no superagent isn’t a requirement.

Perhaps there is an error object inside the response header for the requests? Response Error Object. It might help.

EDIT:
Also the XMLHTTPRequest option in your dev console (in Chrome) is awesome for getting insight on requests.

Also just noticed, looking at the superagent doc’s that the set() method takes two arguments, and you have an object.

Yeah I noticed that when I was messing with my code again so I changed it I still get no JSON data I’m looking up the status code as we speak.