首页 > 解决方案 > 从 Jquery 调用 AWS API 时出现 CORS 错误

问题描述

从 Jquery 调用 AWS API 时出现 CORS 错误。

CORS 已在 API 端启用,我可以使用 react > Axios 进行调用,但我们必须为该应用程序使用 Jquery。

使用此代码:

 $.ajax({
      type: 'POST',
      url: "https://awsapiurlhere",
      crossDomain: true,
      async:true,
      data: {
      aaa: "444",
      bbb: "aaa",
      ccc: "ccc"
      },
      dataType: 'JSON',
      cors: true ,
      contentType:'application/json',
      headers: {
          "Access-Control-Allow-Origin":"*",
      },
      success: function(response, status, xhr) {
        if (response) {
          console.log("The username you typed has been used!", status);
        } else {
           console.log("No responce" , status);
        }
      },
      error: function(xhr, status, error) {
       console.log("Something went wrong!", status );
      }
    });

得到

从源“ https://cdpn.io ”访问“ https://url ”处的 XMLHttpRequest已被 CORS 策略阻止:Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-origin在预检响应中。

标签: jqueryaws-api-gateway

解决方案


您正在发送 Access-Control-Allow-Origin 作为请求的一部分。根据错误消息,CORS 策略不允许请求标头。您不需要在请求中使用此标头,因为它是响应标头。从请求中删除此标头将解决此问题。


推荐阅读