cloudflare js worker允许国家列表并阻止其余国家

时间:2019-05-12 10:33:09

标签: javascript cloudflare worker cloudflare-workers

我正在尝试将以下代码调整为允许列表中的国家/地区,如果不允许,则阻止当前代码,如果列表中的国家/地区,则当前代码执行oppiste阻止,否则为

addEventListener('fetch', event => {
  event.respondWith(blockCountries(event.request))
})

//Add countries to this Set to block them
const countries = new Set([  
  "US", // United States
  "SG", // Singapore 
  "BR"  // Brazil
])

async function blockCountries(request) {
  // Get country value from request headers
  let country = request.headers.get('cf-ipcountry')

  // Find out if country is on the block list
  let countryBlocked = countries.has(country)

  // If it's on the blocked list, give back a 403
  if (countryBlocked){
    return new Response("This page not available in your country",
        { status: 403, statusText: "Forbidden" })
  }

  // Catch-all return of the original response
  return await fetch(request)
}

任何调整此技巧的提示

1 个答案:

答案 0 :(得分:0)

要进行更改,您可以更改以下内容:

let countryBlocked = countries.has(country)

对此:(注意感叹号)

let countryBlocked = !countries.has(country)

感叹号是NOT运算符。因此,如果此请求的国家/地区不在允许的国家/地区中,则此更改会将countryBlocked设置为true

要注意的一件事是,如果给定请求的国家未知,it may show up as "XX"

以下是具有更改和更新注释的完整代码,以反映新行为:

addEventListener('fetch', event => {
  event.respondWith(blockCountries(event.request))
})

// Add countries to this Set to allow them
const countries = new Set([  
  "US", // United States
  "SG", // Singapore 
  "BR"  // Brazil
])

async function blockCountries(request) {
  // Get country value from request headers
  let country = request.headers.get('cf-ipcountry')

  // Check if country is on the allowed list
  let countryBlocked = !countries.has(country)

  // If it's not on the allowed list, give back a 403
  if (countryBlocked){
    return new Response("This page not available in your country",
        { status: 403, statusText: "Forbidden" })
  }

  // Catch-all return of the original response
  return await fetch(request)
}