gpt4 book ai didi

javascript - Api-Version header 未正确发送

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:48 25 4
gpt4 key购买 nike

亲爱的 friend 们,我有一个奇怪的问题,我尝试连接到一个 API,当我尝试在 postman 或 insomnia 中执行 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>

enter image description here

最佳答案

它的 CORS问题,API 服务器缺少 header Access-Control-Allow-Headers 因此您无法设置自定义请求 header ,例如 "Api-Version": "3",解决方案使用 CORS代理或从您的服务器检索数据或要求您的提供商添加它。

与 Postman 的不同之处在于 postman 不询问服务器 API 它只是简单地发送 header ,而 Browser 因为不同的域它会通过使用以下 header 执行 OPTIONS 请求来询问在发出 Post 请求之前。

Access-Control-Request-Headers: api-version,authorization,content-type

然后服务器 API 需要响应 header

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>

关于javascript - Api-Version header 未正确发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com