无法加载 'endpoint':请求 header 字段 If-Modified-Since 不允许在预检响应中被 Access-Control-Allow-Headers

Failed to load 'endpoint': Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response

我已经使用 nodejs 创建了一个 API 服务,当我通过浏览器访问时它工作正常。但是当我尝试从 Web 应用程序(MEAN 应用程序)调用它时,出现 "Failed to load http://localhost:2020/api/posts: Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response" 问题。

在 API 服务的 index.js 中添加了以下代码。

    // Add headers
    app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

并在网络应用程序的控制器中添加了以下行,

app.config(["$routeProvider", "$httpProvider", function ($routeProvider, $httpProvider) {
    $httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
}
]);

但是没有运气添加上面的行。如何解决这个问题?

谢谢。

您需要在您的服务器代码中添加 If-Modified-SinceAccess-Control-Allow-Headers:

res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,If-Modified-Since');

此外,您在客户端上触摸 HTTP header 的部分对我来说似乎毫无用处,我认为您对此无能为力。