javascript 如何在 express.js node.js 中设置 X-Frame-Options

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

How to set X-Frame-Options in express.js node.js

javascriptnode.jsexpressiframeembed

提问by Harshit Laddha

I have some static assets that I want to serve inside iframes of several desktop / mobile web clients.

我有一些静态资产,我想在多个桌面/移动 Web 客户端的 iframe 中提供这些资产。

Now, how do I whitelist a specific set of origins to be allowed setting of X-Frame-Options headers so that the resource can be embedded as iframes inside different desktop / mobile web clients. and for all other origins denies the access to this resource.

现在,我如何将一组特定的源列入白名单以允许设置 X-Frame-Options 标头,以便资源可以作为 iframe 嵌入到不同的桌面/移动 Web 客户端中。对于所有其他来源,拒绝访问此资源。

With a little digging I started off with -

通过一点点挖掘,我开始了 -

const app = express();

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');
    if (req.method === "OPTIONS") res.send(200);
    else next();
}
app.use(allowCrossDomain);

Now here how do I set the X-Frame-Options header with the whitelisted origin values here -

现在在这里我如何使用列入白名单的原始值设置 X-Frame-Options 标头 -

回答by zivce

You should import helmetand use frameguardto get some origins whitelisted. More on this topic: MDN X-FRAME-OPTIONSBest Practice Security

您应该导入头盔并使用frameguard将一些来源列入白名单。有关此主题的更多信息:MDN X-FRAME-OPTIONS最佳实践安全

回答by Edwin Ikechukwu Okonkwo

all you need is helmet

你只需要头盔

npm install helmet --save 

const express = require('express')
const helmet = require('helmet')

const app = express()

app.use(helmet.frameguard())