【问题标题】:XMLHttpRequest blocked by CORS Policy using $.ajax [duplicate]使用 $.ajax 的 CORS 策略阻止 XMLHttpRequest [重复]
【发布时间】:2020-01-30 07:04:58
【问题描述】:

我托盘访问端点并获取令牌,但我有一个错误: 从源“http:localhost:51780”访问“https://ptyi.test.com:8443/users/authenticate”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制-允许-来源”;请求的资源上存在标头。我该如何解决?为什么要通过邮递员访问?提前谢谢!!

       $.ajax({
           type:"POST",
           url: "https://ptyi.test.com:8443/users/authenticate",
           data: { username :"test@sur.com" , password : "ff12dfb3L$"},
           crossDomain: true,
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (result) {
              alert(result)
           },
           error: function (xhr, ajaxOptions, thrownError) {
                      alert(xhr.status + " \n" + xhr.responseText, "\n" + thrownError);
           },
       });
    });

【问题讨论】:

    标签: jquery ajax cors


    【解决方案1】:

    出于安全原因,您不能向在不同端口上运行的端点调用 ajax 请求。 我不知道你的服务器端技术是什么,但是 如果您可以访问https://ptyi.test.com:8443/users/authenticate 的源代码,那么您可以添加 Access-Control-Allow-Origin", "*"

    private void addCorsHeader(HttpServletResponse response){
            //TODO: externalize the Allow-Origin
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
            response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
            response.addHeader("Access-Control-Max-Age", "1728000");
        }
    

    【讨论】:

    • 请问投反对票的原因?
    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 2020-06-13
    • 2021-09-05
    • 1970-01-01
    • 2020-05-30
    • 2019-10-31
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多