Axios Get request data comes back with “data: ↵ ↵ ↵ ↵”

ぐ巨炮叔叔 提交于 2019-12-08 00:35:06

问题


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.


回答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.



来源:https://stackoverflow.com/questions/48352460/axios-get-request-data-comes-back-with-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!