我正在尝试使用Fetch访问API。我不能从头开始编写代码,所以我将这些源代码拼凑在一起,包括API文档源代码:
<script type="text/javascript">
const url = 'https://apis.apprenticeships.sfa.bis.gov.uk/vacancies/v1/apprenticeships/search?standardLarsCodes=465';
var myHeaders = new Headers({
'Ocp-Apim-Subscription-Key':'xxxxxxxxxxxxxxxxxxxxxxxxx',
'Host':'apis.apprenticeships.sfa.bis.gov.uk',
'Access-Control-Allow-Origin':'xxxxxxxxxxxxxxxxxxxxxx'
});
fetch(url, {
mode: 'no-cors',
withCredentials:true,
headers: myHeaders
})
.then(function(response) {
data: "{body}"
})
.catch(function(error) {
console.log('Looks like there was a problem: \n', error);
});
</script>
以下是API文档提供的示例代码(在HTML头中使用Ajax):
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://apis.apprenticeships.sfa.bis.gov.uk/vacancies/v1/apprenticeships/{vacancyReference}?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
},
type: "GET",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
当我从Wordpress网站运行代码时,我收到以下错误:
未捕获SyntaxError:意外标记“<”
当我从本地测试服务器运行时,我得到:
加载资源失败:服务器的响应状态为401(拒绝访问)
你能指出我哪里做错了吗?