0

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

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

调整这个的任何提示

4

1 回答 1

0

为了做出改变,你可以改变这个:

let countryBlocked = countries.has(country)

对此:(注意感叹号)

let countryBlocked = !countries.has(country)

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

需要注意的一件事是,如果某个特定请求的国家/地区不为人所知,它可能会显示为 "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)
}
于 2019-05-14T21:30:06.637 回答