Jquery AJAX:请求的资源上没有“Access-Control-Allow-Origin”标头

我试图从我的localhost:4502端口将数据发布到API。 当我尝试使用POSTMAN将数据发布到此API时,通过提供基本授权密钥将数据添加到后端。 我试图在这里实现Ajax Jquery调用,但得到一个CORS错误。 第一次在jquery我试图发布数据,请在这里帮助,我可以添加。 我有基本授权的API密钥,因为用户名和密码可以留空。

  $(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=="); } }); }); });  

我添加了dataType:’jsonp’,它有效!

 $.ajax({ type: 'GET', crossDomain: true, dataType: 'jsonp', url: '', success: function(jsondata){ } }) 

它是一个CORS问题,你的api无法直接从远程或不同的原点访问,为了允许其他IP地址或其他来源访问你的api,你应该在api的标题上添加’Access-Control-Allow-Origin’,如果您希望所有人都可以访问它,您可以将其值设置为’*’,或者您可以设置特定的域或ips,如’ http://siteA.com ‘或’ http:// 192 。 IP地址 ‘;

在api的标题中包含它,它可能会有所不同,具体取决于您显示json数据的方式,

如果您使用ajax,检索并显示数据,您的标题将如下所示,

 $.ajax({ url: '', headers: { 'Access-Control-Allow-Origin': 'htt://site allowed to access' } data:, type: /* etc */ success: function(jsondata){ } }) 

如果您在服务器端使用NodeJ,只需将这些添加到您的路由中即可

  res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 

那么你的路线会看起来像这样

 router.post('/odin', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); return res.json({Name: req.body.name, Phone: req.body.phone}); 

});

客户端进行Ajax调用

  var sendingData = { name: "Odinfono Emmanuel", phone: "1234567890" }  

您应该在浏览器控制台中将此类内容作为响应

 { name: "Odinfono Emmanuel", phone: "1234567890"} 

享受编码….

Interesting Posts