亲爱的朋友,我遇到一个奇怪的问题,我尝试连接到API,当我尝试在邮递员或失眠症患者中提出API请求时,一切正常。当我在我的网站上甚至在本地主机上使用相同的代码时,潜在客户请求都无法正常运行,并告诉我未定义api版本。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "https://affiliate-api.tradingcrm.com:4477/token",
"method": "POST",
"data": "{ userName: \"alpt\", password: \"Alpt@12345\" }"
}
$.ajax(settings).done(function (response) {
var settings2 = {
"async": true,
"crossDomain": true,
"url": "https://affiliate-api.tradingcrm.com:4477/accounts/lead",
"method": "POST",
"headers": {
"Authorization": "Bearer " + response.Token,
"Api-Version": "3",
"Content-Type": "application/json"
},
"data": "{firstName:\"test\",lastName:\"test2\",email:\"test@test.test\"}"
}
$.ajax(settings2).done(function (response2) {
console.log(response2.accountId);
});
});
</script>
答案 0 :(得分:5)
其CORS问题,API服务器缺少标头Access-Control-Allow-Headers
,因此您无法设置自定义请求标头,例如"Api-Version": "3"
,解决方案使用CORS代理或从服务器检索数据或询问您的提供者来添加它。
Postman与Postman的不同之处在于Postman并不询问服务器API,它只是发送标头,而Browser
是因为它与其他Domain的要求是,它会通过对OPTIONS
之前的标头执行Post
请求提出要求。
Access-Control-Request-Headers: api-version,authorization,content-type
然后,服务器API需要使用标头进行响应
Access-Control-Allow-Headers: api-version,authorization,content-type
CORS代理测试:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "https://affiliate-api.tradingcrm.com:4477/token",
"method": "POST",
"data": "{ userName: \"alpt\", password: \"Alpt@12345\" }"
}
$.ajax(settings).done(function(response) {
console.log('requesting using CORS Proxy.....');
var settings2 = {
"async": true,
"crossDomain": true,
"url": "https://cors-anywhere.herokuapp.com/https://affiliate-api.tradingcrm.com:4477/accounts/lead",
"method": "POST",
"headers": {
"Authorization": "Bearer " + response.Token,
"Api-Version": "3",
"Content-Type": "application/json"
},
"data": "{firstName:\"test\",lastName:\"test2\",email:\"test@test.test\"}"
}
$.ajax(settings2)
.done(function(response2) {
console.log(response2.accountId);
})
.fail(function(jqXHR, textStatus) {
console.log(textStatus);
console.log(jqXHR.responseText);
});
})
</script>