【问题标题】:whateverorigin.org | YQL | CORS not working不管起源.org | YQL | CORS 不工作
【发布时间】:2017-11-16 01:09:20
【问题描述】:

我已经尝试了所有这三种方法,但由于某种原因,它们给出了错误,因为跨域访问被拒绝。我在我的应用程序的各个地方都使用了 YQL,但它现在也不起作用。

JSFIDDLE

<script>
$(function() {
    $.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){
        alert(data.contents);
    });
});

</script>

<div id="output"></div>

可以解决或更可靠的替代方案吗?

【问题讨论】:

  • 您是否尝试过使用https?如果我使用"https://whateverorigin.herokuapp.com/get?url",它对我有用
  • 是类似于Blocked loading mixed active content "url" 的错误-whateverorigin.org 被破坏并没有帮助
  • I have tried all three - 三个都是什么?
  • 我也尝试过https...这三个都是yqlcorswhateverorigin.org
  • @JaromandaX 是的,我认为 whateverorigin.org 已损坏,但 yql 和 cors 也无法正常工作

标签: javascript jquery html cors yql


【解决方案1】:

您尝试访问的 API 可能未启用 CORS。

你可以考虑在你的请求AJAX请求中使用JSONP

$.ajax({ 
  type: "GET",
  url: 'http://www.whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?',
  dataType: 'jsonp',
  success: function(data) { alert(data.contents); }
})

另一种方法是创建一个服务器,通过路由执行 API 请求,这不是您通过客户端执行的直接解决方案。服务器将充当代理,以便您可以对服务器进行 AJAX 调用,以对您正在执行 GET 请求的端点进行 API 调用。当然,您必须在此代理服务器上启用 CORS。

在 node.js 中,它看起来像...

const express = require('express')
const axios = require('axios')
const cors = require('cors')
const app = express()

app.use(cors())
app.get('/nameofroute', (req, res) => {
  axios.get('http://www.whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?'
}).then(response => res.json(response))
  .catch(err => res.json(err))
}

app.listen(8080, () => { console.log('listening on:8080') }

在前端,您可以对刚刚创建的上述服务器执行 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2023-01-11
    • 2017-07-14
    • 2018-06-01
    • 2013-08-25
    • 2014-11-05
    相关资源
    最近更新 更多