使用GET方法在Jquery中的CORS问题

时间:2017-06-22 13:17:28

标签: javascript jquery ajax http get

我正在通过可用GET方法的URL获取数据。 我使用Jquery获取JSON并将其解析为HTML表。

但是,我无法解决CORS问题。我添加了代码:

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'True');
res.header('Access-Control-Allow-Headers', 'accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token');

我还安装了chrome扩展来启用CORS。

然而,它们都没有奏效。我也试过直接使用XMLHttpRequest,它仍然没有工作......

这是我使用Jquery的代码:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
 var url = 'https://www.probancemail.com/rest/v2/stats/RT1-PREM_DE?&token=5eX8dIljx9fWOvFu7WO22uL3EEYSN8PEciwZKdYqKxK6HOsHxjyYQpVBQiSLEGOJkId9wTNOAUpGRPfPWJgXV5u8s9EUL9hVeGSa'
function FIXCORS(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'True');
res.header('Access-Control-Allow-Headers', 'accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token');
 // intercept OPTIONS method
if ('OPTIONS' == req.method) {
  res.send(200);
}
else {
  next();
}
};
$(document).ready(function () {
$.getJSON(url,
function (json) {
tr = $("<tr></tr>")
for (var i = 0; i < json.results.length; i++) {
var td = "<td>" + json.results[i].address_components[0].long_name+"</td>"
$(tr).append(td);
}
$('table').append($(tr));
});
});
</script>
</head>
<body>
<table></table>
</body>
</html>

它始终显示No&#39; Access-Control-Allow-Origin&#39;的错误消息。标头出现在请求的资源上。起源&#39; null&#39;因此不允许访问。

我的代码是直接使用HTTP请求的,它基于这篇文章:https://www.html5rocks.com/en/tutorials/cors/

<!DOCTYPE html>
<html><meta charset="utf-8"/>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

function reqListener() {
console.log(this.responseText);
}
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('/campaign');
}

// Make the actual CORS request.
function makeCorsRequest() {
// This is a sample server that supports CORS.
var url = 'https://www.probancemail.com/rest/v2/stats/RT1-PREM_DE?&token=5eX8dIljx9fWOvFu7WO22uL3EEYSN8PEciwZKdYqKxK6HOsHxjyYQpVBQiSLEGOJkId9wTNOAUpGRPfPWJgXV5u8s9EUL9hVeGSa';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
 }

 // Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
 };

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
 xhr.send();
}
</script>
</head>
<body>

<div id = "div"></div>
<button type = "button" onclick = "makeCorsRequest">Retrieve Report Data</button>

</body>
</html>

这个没有错误信息,但根本没有结果...... 有人有想法吗? 欢迎任何反馈! 非常感谢提前!

1 个答案:

答案 0 :(得分:1)

服务器上应支持CORS。如果发送跨域请求,jQuery会向请求添加Origin: http://example.com标头,并在响应中预期Access-Control-Allow-Origin: http://example.comAccess-Control-Allow-Origin: *标头。

您可以在MDN上阅读有关CORS的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

P.S。关于脚本中的FIXCORS函数,我假设您已从某些Node.js CORS指南中复制了该函数,它也应该放在服务器上