typescriptaxios

Axios query paramaters?


when using postman I just enter query paramaters but in axios I am unable to do. I have to use string addition. is this bad?

 const url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/ImageSearchAPI?pageNumber="+data.pageNumber+"&pageSize="+data.pageSize+"&q="+data.q+"&autoCorrect=true"
          const result = await axios.default.get(url,headers)
          const values = result.data.value
          for (const value of values) {
              const imageURL = value.url as string
              res.images.push(imageURL)
          }
         
          response.send(res)

thanks. I find axios to be really hard to use... it has 13m downloads maybe im using a hammer when all I need is a tap. Should I switch to lighter weight http service like unirest?


Solution

  • The 2nd parameter to axios.get() is the Axios options: It will serialize options.params and add it to the query string. Try the following:

    const res = await axios.get(
      'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/ImageSearchAPI',
      {
        params: 
          {
             pageNumber:data.pageNumber,
             pageSize:data.pageSize,
             q:data.q,autoCorrect:true
           },
        headers
      }
    );
    

    Generally you must format request with paramters like this:

    const res = await axios.get( URL, {params:{key:val},headers});