简体   繁体   中英

Node.js helmet and swagger-ui

I am using a swagger for API documentation in Node.js. Now I want to use helmet for security, but when I am using helmet, error occur. However, if I place the helmet below the router for swagger, then it works fine, which means helmet do something that makes swagger-ui not be loaded.

Below code is how I used helmet.

var helmet = require('helmet')
app.use(helmet());

Below image is the error from swagger

在此处输入图像描述

Fix to allow cors but still got an error.

//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());

You need to enable CORS, so that it sends the Access-Control-Allow-Origin: * header in responses. CORS stands for cross origin resource sharing. It opens up the content we intend to server to public for universal JavaScript/browser access.

example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM