我试图用post请求发送文件到我的服务器,但当它发送时,它会导致错误:

Access-Control-Allow-Headers不允许请求报头字段Content-Type。

所以我谷歌了这个错误,并添加了标题:

$http.post($rootScope.URL, {params: arguments}, {headers: {
    "Access-Control-Allow-Origin" : "*",
    "Access-Control-Allow-Methods" : "GET,POST,PUT,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
}

然后我得到错误:

Access-Control-Allow-Headers不允许请求报头字段Access-Control-Allow-Origin

所以我谷歌了一下,我能找到的唯一类似的问题是提供了一半的答案,然后关闭为跑题。我应该添加/删除什么头?


当前回答

在Asp Net Core中,快速让它工作;在Startup.cs中,配置add方法

app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

其他回答

这是后台问题。如果在后端使用sails API更改cors.js并在这里添加您的文件

module.exports.cors = {
  allRoutes: true,
  origin: '*',
  credentials: true,
  methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
  headers: 'Origin, X-Requested-With, Content-Type, Accept, Engaged-Auth-Token'
};

如果这对任何人都有帮助,(即使这有点可怜,因为我们必须只允许用于开发目的)这里有一个Java解决方案,因为我遇到了同样的问题。 [编辑]不要使用通配符*,因为它是一个糟糕的解决方案,如果你真的需要在本地工作,请使用localhost。

public class SimpleCORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "my-authorized-proxy-or-domain");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}

如果有人在使用快速服务器时遇到此问题,请添加以下中间件

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

对我来说,添加以下到我的服务器的网页。配置文件:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="https://other.domain.com" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE" />
            <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With" />
        </customHeaders>
    </httpProtocol>
<system.webServer>

对我来说,我在web.config中有通配符“*”Access-Control-Allow-Headers:

<add name="Access-Control-Allow-Headers" value="*" />

这个解决方案适用于大多数导航器,但不适用于Safari或IE

结果证明,解决方案是手动添加所有自定义头到web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="https://somedomain.com" />
            <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS,PUT,DELETE" />
            <add name="Access-Control-Allow-Headers" value="custom-header1, custome-header2, custome-header3" />
        </customHeaders>
    </httpProtocol>
<system.webServer>