Jquery AJAX:请求的资源上不存在“Access-Control-Allow-Origin”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47523265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:26:50  来源:igfitidea点击:

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

jqueryajaxcorsaem

提问by Ashish Rai

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.

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

  <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>

回答by Hunter

I have added dataType: 'jsonp' and it works!

我添加了 dataType: 'jsonp' 并且它有效!

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

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More

JSONP 是一种发送 JSON 数据而无需担心跨域问题的方法。阅读更多

回答by apelidoko

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';

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

Include this on your api's header, it may vary depending on how you are displaying json data,

将此包含在您的 api 标题中,它可能会因您显示 json 数据的方式而异,

if your using ajax, to retrieve and display data your header would look like this,

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

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

   }
})

回答by Odin

If you are using NodeJs for your server side, just add these to your route and you will be Ok

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

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

Your route will then look somehow like this

然后你的路线看起来像这样

    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});
});

Client side for Ajax call

Ajax 调用的客户端

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

<script>
  $(document).ready(function(){

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

您的浏览器控制台中应该有类似的内容作为响应

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

Enjoy coding....

享受编码......

回答by Daniel Stahl

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

请注意对所有请求使用常量 HTTPS 或 HTTP。我有同样的错误消息:“请求的资源上不存在‘Access-Control-Allow-Origin’标头。”

回答by Johnson

If the requested resource of the server is using Flask. Install Flask-CORS.

如果请求的服务器资源使用的是 Flask。安装Flask-CORS