我试图用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

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


当前回答

如果你正在使用localhost和PHP来解决这个问题:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type'); 

从您的前端使用:

{headers: {"Content-Type": "application/json"}}

boom没有更多的问题来自localhost!

其他回答

在我的例子中,我将几个参数作为@HeaderParam接收到一个web服务方法中。

这些参数必须在你的CORS过滤器中声明:

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        ...
        headers.add("Access-Control-Allow-Headers", 
        /*
         * name of the @HeaderParam("name") must be declared here (raw String):
         */
        "name", ...);
        headers.add("Access-Control-Allow-Credentials", "true");
        headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");   
    }
}

请求报头字段Access-Control-Allow-Origin被Access-Control-Allow-Headers错误不允许 表示HTTP报头的Access-Control-Allow-Origin字段不被响应处理或允许。从请求头中删除Access-Control-Allow-Origin字段。

如果你正在使用localhost和PHP来解决这个问题:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type'); 

从您的前端使用:

{headers: {"Content-Type": "application/json"}}

boom没有更多的问题来自localhost!

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

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>