我尝试使用 AJAX 调用 Yelp Fusion API,但出现以下错误。有人可以帮我弄清楚这是怎么回事吗?
api.yelp.com/v3/:1 加载资源失败:服务器响应状态为 403 ()
index.html:1 从源“null”访问“https://api.yelp.com/v3/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“访问” -Control-Allow-Origin'标头存在于请求的资源上。
这是我正在使用的代码:
var queryURL = "https://api.yelp.com/v3/";
var apiKey = "my key"
$.ajax({
url: queryURL,
method: "GET",
headers: {
"accept": "application/json",
"Access-Control-Allow-Origin":"*",
"Authorization": `Bearer ${apiKey}`
}
}).then(function(res) {
var results = res.data
console.log(results);
});
尝试使用 CORSanywhere 代理,将密钥插入下面的片段中并尝试一下:
// JavaScript Document
var queryURL = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/";
var apiKey = "my key";
$.ajax({
url: queryURL,
method: "GET",
headers: {
"accept": "application/json",
"x-requested-with": "xmlhttprequest",
"Access-Control-Allow-Origin":"*",
"Authorization": `Bearer ${apiKey}`
},
success: function(result){
console.log(result);
}
});
我在使用 Google 的 API 和 Yelp 的 API 时都遇到了类似的问题。
Access to fetch at
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=bar&location=30.2849231%2C-97.7366316&radius=5000&key={YOUR_API_KEY}' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
我也尝试过使用 cors-anywhere 代理,但简单地在前面添加代理 URL 不起作用,代理向我发送了错误。
> GET /https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=30.2849231%2C-97.7366316&radius=3000&keyword=bar&key={YOUR_API_KEY} HTTP/1.1
> Host: cors-anywhere.herokuapp.com
>
< HTTP/1.1 400 Header required
< Access-Control-Allow-Origin: *
< Access-Control-Expose-Headers: access-control-allow-origin
<
Missing required request header. Must specify one of: origin,x-requested-with
CORSAnywhere 代理似乎需要添加两个标头,因为他们希望防止人们将它们用作匿名浏览器代理。
解决方案似乎是添加 origin 或 x-requested-with HTTP 标头作为 HTTP 响应正文中指定的代理。
这是对我有用的 JavaScript 获取请求:
var apiUrl =
"https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=" +
search + "&location=" + latitude + "%2C" + longitude + "&radius=" + radius + "&key=" + myapikeys.google;
fetch(apiUrl, {
method: "GET",
headers: {
Origin: "null",
Accept: "application/json",
},
})
.then(function (response) {
if (response.ok) {
console.log(response);
response.json().then(function (data) {
console.log(data);
});
} else {
alert("Error: " + response.statusText);
}
})
.catch(function (error) {
alert("Unable to connect");
});