jjzjj

node.js - 无法加载 'endpoint' : Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response

coder 2023-11-01 原文

我使用 nodejs 创建了一个 API 服务,当我通过浏览器访问时它工作正常。但是当我尝试从 Web 应用程序(MEAN 应用程序)调用它时,得到 “无法加载 http://localhost:2020/api/posts:请求 header 字段 If-Modified-Since 不允许被 Access-Control-Allow - 预检响应中的 header ” 问题。

在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();
});

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

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

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

谢谢。

最佳答案

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

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

此外,您在客户端上触摸 HTTP header 的部分对我来说似乎毫无用处,我认为您无法用它做任何事情。

关于node.js - 无法加载 'endpoint' : Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47532360/

有关node.js - 无法加载 'endpoint' : Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response的更多相关文章

随机推荐