我试过这三种方法,但由于某种原因,它们会导致跨域访问被拒绝。我在我的应用程序中的不同地方使用了YQL,但现在它也不起作用。
<script>
$(function() {
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){
alert(data.contents);
});
});
</script>
<div id="output"></div>
能工作或更可靠的替代方案吗?
发布于 2017-06-13 20:33:13
您要访问的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。
https://stackoverflow.com/questions/44535324
复制