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

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

问题描述

我开发了一个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,状态:0,statusText:语法错误:无法执行
执行'setRequestHeader'... -Origin:'不是有效的HTTP标头
字段名称。}错误DOMException:无法在'XMLHttpRequest'上执行'setRequestHeader'
:'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将CORS头添加到http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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