2

I am using Axios to make a get request to a Jobs API site. Whenever I console.log the response, I can't seem to use it. The object that comes back is {data: "↵ ↵ ↵ ↵"}, but it looks like JSON.

const url = //api string content

axios.get(url)
.then(function(res){
    console.log(res);
})
.catch(function(){
    console.log("err");
})

If I console.log(res.data), then it doesn't come back parsed in JSON. It looks like it's returning a function with all the data. It looks like displayJobs({"keys": "values"}). I can't get res.data.displayJobs. When I go directly to the link, my JSON viewer parses it normal. How can I get the data to come back as JSON format? ex: res.data.jobTitle

Thank you for any help. I've had a few successful API requests on other projects, but I am still fairly new so I hope this isn't a dumb question.

  • It sounds like the endpoint is serving your app JSONP, here's an answer that explains how you can work with it: https://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms – Chris Riebschlager Jan 20 '18 at 04:10
  • Okay, that seems like it makes a lot of sense. Seems like it should work. Thanks. – Michael Koska Jan 20 '18 at 04:22

1 Answers1

1

It looks like you're working with a JSONP endpoint. You cannot use axios with JSONP endpoints. I'd recommend either:

  1. Find an alternate, non-JSONP endpoint for the API you are using, or
  2. Try the jsonp package instead for that particulate endpoint. https://github.com/axios/axios/blob/master/COOKBOOK.md#jsonp

As noted in the comments, you can learn more about JSONP here: https://stackoverflow.com/a/3840118/3814251


If you're wondering how I knew how to answer your question (as I've found it helpful to learn how other people find answers), it's because I recognized the retrieved data as what JSONP endpoints normally respond with. I then Googled "axios jsonp" to see if axios worked with JSONP endpoints, which let me to https://github.com/axios/axios/issues/75 (where it's noted that axios does NOT offer jsonp be support). I followed the links in that GitHub thread and wrote my answer afterwards.

therobinkim
  • 2,500
  • 14
  • 20
  • I've heard of JSONP, I just never knew anything about it. I was trying jQuery as well and even an XMLHttpRequest and just couldn't get anything. Well, I learned something new. Thanks! – Michael Koska Jan 20 '18 at 04:33