問題描述
我正在嘗試從我的 localhost:4502 端口將數(shù)據(jù)發(fā)布到 API.當(dāng)我嘗試使用 POSTMAN 將數(shù)據(jù)發(fā)布到此 API 時(shí),通過提供基本授權(quán)密鑰將數(shù)據(jù)添加到后端.我試圖在 Ajax Jquery 調(diào)用中實(shí)現(xiàn)相同的功能,但出現(xiàn) CORS 錯(cuò)誤.我第一次在 jquery 中嘗試發(fā)布數(shù)據(jù),請(qǐng)?jiān)谶@里提供幫助,我可以添加什么.我已經(jīng)獲得了基本授權(quán)的 API 密鑰,因?yàn)橛脩裘兔艽a可以留空.
I am trying to post data to an API from my localhost:4502 port. When i tried to post data to this API using POSTMAN the data got added in the backend by providing the Basic Authorization key. The same i am trying to implement here in the Ajax Jquery call, but getting an CORS error. First time in jquery i am trying to post the data, please help here, what i can add. I have got the API key to for the Basic Authorization as a Username and Password can be left blank.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#Save").click(function(){
var person = new Object();
person.Name = $('#Name').val();
person.EmailAddress = $('#EmailAddress').val();
person.CustomFields = [0];
person.CustomFields[0].Key = "[Country]";
person.CustomFields[0].Value = $('#Country').val();;
$.ajax({
url: 'https://api.createsend.com/api/v3.1/subscribers/7c7a6087b0e450ad72b38be83098e271.json',
type: 'POST',
dataType: 'json',
data:person,
success: function(data,textStatus,xhr){
console.log(data);
},
error: function(xhr,textStatus,errorThrown){
console.log('Error Something');
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic OTdlMjVmNWJiMTdjNzI2MzVjOGU3NjlhOTI3ZTA3M2Q5MWZmMTA3ZDM2YTZkOWE5Og==");
}
});
});
});
</script>
推薦答案
我已經(jīng)添加了 dataType: 'jsonp' 并且它有效!
I have added dataType: 'jsonp' and it works!
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: '',
success: function(jsondata){
}
})
JSONP 是一種發(fā)送 JSON 數(shù)據(jù)的方法,無需擔(dān)心跨域問題.閱讀更多
JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More
這篇關(guān)于Jquery AJAX:請(qǐng)求的資源上不存在“Access-Control-Allow-Origin"標(biāo)頭的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!