使用 Ajax 向 http 请求添加 CORS 标头 [英] Add CORS header to an http request using Ajax

查看:51
本文介绍了使用 Ajax 向 http 请求添加 CORS 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个 Restfull 应用程序,我想添加另一个 Web 应用程序来使用它的服务,所以我进行了这个 Ajax 调用:

I have developed a Restfull application and I'd like to add another web application to consume its services so I make this Ajax call :

 $.ajax({
            type: "Post",
            async: false,
            url: "ip_adress/Inviter/api/Account/Register",
            data: donne,
            headers: {  "Access-Control-Allow-Origin:": "*"},
            success: function (data) {
                console.log(data);
                var tab = [];
                tab["username"] = username;
                tab["password"] = pwd;
                var isLogged = Login.CheckCredential(tab, username);
                return isLogged;
            },
            error: function (xhr, status, error) {
                console.log(xhr);
                console.log(status);
                console.log(error);
            }

        });

我收到此异常:

对象 {readyState: 0, status: 0, statusText: "SyntaxError: Failed to执行 'setRequestHeader' ...-Origin:' 不是有效的 HTTP 标头字段名称."} 错误 DOMException:无法执行setRequestHeader"关于XMLHttpRequest":Access-Control-Allow-Origin:"不是有效的HTTP 标头字段名称.

Object {readyState: 0, status: 0, statusText: "SyntaxError: Failed to execute 'setRequestHeader' …-Origin:' is not a valid HTTP header field name."} error DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Access-Control-Allow-Origin:' is not a valid HTTP header field name.

所以我需要知道:

  • 在这种情况下如何启用 CORS?

  • How can I enable the CORS in this situation?

如何修复我的代码?

推荐答案

你不能这样授权自己.这是一个响应标头;规范中的详细信息.您要向其发送请求的服务器必须将该标头发回,以便让浏览器知道允许您的页面向该服务器发送 ajax 请求是可以的.如果您尝试请求的服务器不允许您的源,则您无法在客户端代码中执行任何操作.

You can't authorize yourself like that. It's a response header; details in the specification. The server you're sending the request to has to send that header back to let the browser know it's okay to allow your page to send an ajax request to that server. There's nothing you can do in your client-side code if the server you're trying to request from doesn't allow your origin.

这篇关于使用 Ajax 向 http 请求添加 CORS 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆