Google News API gives an error Uncaught SyntaxError: Unexpected token ')'

感情迁移 提交于 2019-12-11 04:24:35

问题


Originally I wrote some code like this:

var val="MSFT";
$.get('https://www.google.com/finance/company_news?q='+val+'&output=rss', 
  function (data) {
    console.log(data);
});

And that code is working fine locally. But when I am trying to call this same function from GitHub it is giving me an error about CORS.

So, I am trying with the following client-side code:

var nws_lbl = "MSFT";
var news_url = 'https://www.google.com/finance/company_news?q='+nws_lbl+'&output=rss&callback=? ';

$.ajax({
    url: news_url,
    data: {
       format: 'json'
    },
    error: function () {
        console.log("Error while getting data");
    },
    dataType: 'jsonp',
    success: function (data) {
        console.log(data);
    }
});

But with that I am getting the following error:

In the network I am getting 200 that means response is correct.

It is always going to the error. Not sure what I am missing. Can anyone help?


回答1:


You can get around the CORS restriction by making your request through a CORS proxy, like this:

var val="MSFT",
    proxyUrl = 'https://cors-anywhere.herokuapp.com/',
    targetUrl = 'https://www.google.com/finance/company_news?q='+val+'&output=rss';

$.get(proxyUrl + targetUrl, 
  function (data) {
    console.log(data);
});

The proxy makes the request to targetUrl, gets the response, adds the Access-Control-Allow-Origin response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin header added is what the browser sees, so the browser lets your frontend code actually access the response.


As far as the second code snippet in the question, I think the reason it doesn’t work for you is that https://www.google.com/finance/company_news doesn’t have any way to return JSONP. So the format and callback params don’t seem to cause what you want but are causing some non-JSONP response instead, which your code fails to parse because it’s not in the expected format.



来源:https://stackoverflow.com/questions/43314070/google-news-api-gives-an-error-uncaught-syntaxerror-unexpected-token

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