jQuery-CORS错误 [英] JQuery - CORS Error
问题描述
我正在尝试使用JQuery进行API调用.如果未通过按下提交按钮触发呼叫,则该呼叫将非常正常.在提交事件上触发它的那一刻,我收到一条错误消息:
I'm trying to do an API call using JQuery. The call works perfectly fine if it is not triggered by the press of a submit button. The moment I trigger it on the submit event, I get an error saying:
跨域请求被阻止:相同来源策略"不允许读取 https://api.github.com/search/repositories?q=jquery_language:javascript&sort=starts . (原因:CORS请求失败). 引用
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.github.com/search/repositories?q=jquery_language:javascript&sort=starts. (Reason: CORS request failed). Blockquote
这是代码:
var mainForm = $("#mainForm");
mainForm.on("submit", function(){
var gitHubSearch = "https://api.github.com/search/repositories?q=jquery_language:javascript&sort=starts"
jQuery.support.cors = true;
$.get(gitHubSearch)
.success(function(r) {
console.log(r.items.length);
displayResults(r.items);
})
.fail(function(err) {
console.log("Failed to query GitHub");
resultList.text("The API Call has failed.");
})
.done(function() {
console.log("API Call completed");
});
});
推荐答案
需要访问控制-允许-起源
此标头必须包含在所有有效的CORS响应中;省略标头将导致CORS请求失败.
This header must be included in all valid CORS responses; omitting the header will cause the CORS request to fail.
Access-Control-Allow-Origin: * // allows Cross-Origin Request
这篇关于jQuery-CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!