问题描述
我在 Node.js 中使用 swagger 来编写 API 文档。 现在我想使用头盔来确保安全,但是当我使用头盔时,会发生错误。 但是,如果我将头盔放在路由器下方以进行 swagger,则它可以正常工作,这意味着头盔会执行某些使 swagger-ui 无法加载的操作。
下面的代码是我如何使用头盔。
var helmet = require('helmet')
app.use(helmet());
下图是swagger的错误
修复以允许 cors 但仍然出现错误。
//allow cors
app.use(function(req,res,next) {
res.header("Access-Control-Allow-Origin","*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
next();
});
// use helmet
var helmet = require('helmet')
app.use(helmet());
解决方法
您需要启用 CORS ,以便它在响应中发送 Access-Control-Allow-Origin: * 标头。 CORS 代表跨源资源共享。它向公众开放了我们打算提供的内容,以便通用 JavaScript/浏览器访问。
示例:
app.use(function(req,res,next) {
res.header("Access-Control-Allow-Origin","YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
next();
});