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

时间:2017-04-10 02:14:42

标签: google-api cors client-side

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:

enter image description here

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

enter image description here

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

1 个答案:

答案 0 :(得分: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.