javascript 如何在Node js中将子域白色名单

mccptt67  于 2023-01-11  发布在  Java
关注(0)|答案(2)|浏览(83)

我使用下面的正则表达式将域列入白名单,但下面的代码xxx.sampledomain.com不起作用

let url = req.headers.origin.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0]
  let client = CLIENTS.filter(client => client.websiteAddress.replace('www.', '') === url)[0];

请引导

ni65a41a

ni65a41a1#

我正在添加一个代码。它将检查. allow是否为该子域

// List of allowed subdomains
const allowedSubdomains = ["subdomain1", "subdomain2", "subdomain3"];

const subdomainRegex = new RegExp(`^(?:https?:\/\/)?(?:www\.)?(${allowedSubdomains.join("|")})\.`);

// Function to check if a subdomain is allowed
function isAllowedSubdomain(subdomain) {
  return subdomainRegex.test(subdomain);
}

例如:

let subdomain = req.headers.origin.match(subdomainRegex)[1];

// Extract the subdomain from the origin

if (isAllowedSubdomain(subdomain)) {
  console.log("Allow this subdomain")
} else {
  console.log("This subdomain is not allowed")
}

如果你有任何问题,你可以问

kb5ga3dv

kb5ga3dv2#

您可以使用cors,这是一个npm库,可以帮助您实现相同的功能。

var express = require('express')
var cors = require('cors')
var app = express()
 
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
 
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
 
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

相关问题