jQuery 错误:Access-Control-Allow-Headers 不允许请求标头字段 Content-Type

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12409600/
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 11:38:39  来源:igfitidea点击:

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

jqueryasp.net-mvc-4asp.net-web-apioauth-2.0cors

提问by Kishore

I created an mvc4 web api project using vS2012. I used following tutorial to solve the Cross-Origin Resource Sharing, "http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx". It is working successfully, and i post data from client side to server successfully.

我使用 vS2012 创建了一个 mvc4 web api 项目。我使用以下教程来解决跨域资源共享,“http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api- rc-version.aspx”。它工作成功,我成功地将数据从客户端发布到服务器。

After that for implementing Autherization in my project, I used the following tutorial to implement OAuth2, "http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx". This is help me for getting RequestToken on client side.

在我的项目中实现身份验证之后,我使用以下教程来实现 OAuth2,“http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for -mvc-two-legged-implementation.aspx”。这有助于我在客户端获取 RequestToken。

But when i post data from client side, i got the error, "XMLHttpRequest cannot load http://. Request header field Content-Type is not allowed by Access-Control-Allow-Headers."

但是,当我从客户端发布数据时,出现错误 “XMLHttpRequest 无法加载 http://。Access-Control-Allow-Headers 不允许请求标头字段 Content-Type。”

My client sidecode look like,

我的客户端代码看起来像,

 function PostLogin() {
    var Emp = {};            
    Emp.UserName = $("#txtUserName").val();             
    var pass = $("#txtPassword").val();
    var hash = $.sha1(RequestToken + pass);
            $('#txtPassword').val(hash);
    Emp.Password= hash;
    Emp.RequestToken=RequestToken;
    var createurl = "http://localhost:54/api/Login";
    $.ajax({
        type: "POST",
        url: createurl,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(Emp),
        statusCode: {
                200: function () {
                $("#txtmsg").val("done");                       
                toastr.success('Success.', '');                         
                }
                },
        error:
            function (res) {                        
                toastr.error('Error.', 'sorry either your username of password was incorrect.');            
                }
        });
    };

My api controllerlook like,

我的api 控制器看起来像,

    [AllowAnonymous]
    [HttpPost]
    public LoginModelOAuth PostLogin([FromBody]LoginModelOAuth model)
    {
        var accessResponse = OAuthServiceBase.Instance.AccessToken(model.RequestToken, "User", model.Username, model.Password, model.RememberMe);

        if (!accessResponse.Success)
        {
            OAuthServiceBase.Instance.UnauthorizeToken(model.RequestToken);
            var requestResponse = OAuthServiceBase.Instance.RequestToken();

            model.ErrorMessage = "Invalid Credentials";

            return model;
        }
        else
        {
            // to do return accessResponse

            return model;
        }

    } 

My webconfigfile look like,

我的webconfig文件看起来像,

 <configuration>
   <configSections>   
   <section name="entityFramework"    type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <section name="oauth" type="MillionNodes.Configuration.OAuthSection, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
  <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
  <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
  <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<oauth defaultProvider="DemoProvider" defaultService="DemoService">
<providers>
  <add name="DemoProvider" type="MillionNodes.OAuth.DemoProvider, MillionNodes" />
</providers>
<services>
  <add name="DemoService" type="MillionNodes.OAuth.DemoService, MillionNodes" />
</services>
</oauth>
<system.web>
 <httpModules>
   <add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
  </httpModules>
 <compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
</system.web>
<system.webServer>
 <validation validateIntegratedModeConfiguration="false" />      
  <modules>
      <add name="OAuthAuthentication"     type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral" preCondition="" />
 </modules>
 <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
<dotNetOpenAuth>
<messaging>
  <untrustedWebRequest>
    <whitelistHosts>
      <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
      <!--<add name="localhost" />-->
    </whitelistHosts>
  </untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />

回答by Mark Jones

As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headersjust add the additional header to your web.config like so...

正如这篇文章所暗示的那样,Chrome 中错误:内容类型不允许访问控制-允许-标头只是将附加标头添加到您的 web.config 中,如下所示......

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
  </customHeaders>
</httpProtocol>

回答by user1429980

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Originto *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

这很可能是由于跨域请求,但也可能不是。对我来说,我一直在调试 API 并将 设置Access-Control-Allow-Origin*,但似乎最新版本的 Chrome 需要额外的标头。如果您使用的是 PHP,请尝试将以下内容添加到您的文件中:

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

Make sure that you haven't already used headerin another file, or you will get a nasty error. See the docsfor more.

确保你还没有header在另一个文件中使用过,否则你会得到一个令人讨厌的错误。请参阅文档了解更多信息。

回答by Danny22

I know it's an old thread I worked with above answer and had to add:

我知道这是我在上面的答案中使用的旧线程,必须添加:

header('Access-Control-Allow-Methods: GET, POST, PUT');

So my header looks like:

所以我的标题看起来像:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

And the problem was fixed.

问题得到了解决。

回答by Nick Woodhams

For Nginx, the only thing that worked for me was adding this header:

对于 Nginx,唯一对我有用的是添加这个标头:

add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';

Along with the Access-Control-Allow-Origin header:

连同 Access-Control-Allow-Origin 标头:

add_header 'Access-Control-Allow-Origin' '*';

Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.

然后重新加载 nginx 配置,效果很好。信用https://gist.github.com/algal/5480916