javascript - 为什么三元运算符默认为 true

标签 javascript node.js express

我有以下代码:

const production = process.env.PRODUCTION
console.log(production)

const corsOptions = {
    origin: production ? 'https://myproductionurl' : 'http://localhost:3000',
    credentials: true
}

console.log(corsOptions)


app.use(cors(corsOptions))

当我运行此代码时,第一个 console.log 会根据需要返回 false,但第二个 console.log 语句会返回生产 URL,就好像变量为 true 一样。

不知道为什么会这样,如果有人发现了什么,请告诉我!

此外,如果我删除三元和 URL 来测试发生了什么,那么我将在 corsOptions 中得到 origin: false 这让我更加难过!

最佳答案

环境变量总是字符串,除非它们没有被设置,在这种情况下它们将是undefined

如果它正在记录 false,那么您已将其设置为字符串 "false",这是一个真值。

您可以明确地测试它:

production !== 'false' ? 'https://myproductionurl' : 'http://localhost:3000',

...尽管您可能应该编写一个比以下更健壮的测试:

const isProduction = () => {
    const env = process.env.PRODUCTION; 
    if (!env) return false;
    if (env === "false") return false;
    return true;
}

然后

isProduction() ? 'https://myproductionurl' : 'http://localhost:3000',

关于javascript - 为什么三元运算符默认为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73209293/

相关文章:

ajax - Angular JS *非 SPA* SEO

javascript - 了解 Express.js 中的中间件和路由处理程序

node.js - 即使请求有正文,环回自定义路由 req 对象也有空的 body 属性

javascript - 将 javascript 数组加载到 Chartist.js 作为系列

javascript - 动态 php 和 html 表单,带有数量、价格和总 JavaScript 计算

javascript - 由于类分配延迟,onclick 函数需要双击

javascript - ReactJS 当使用 HTML 属性被选中时,reactjs 不允许选择复选框

javascript - Passport 身份验证回调而不是重定向

javascript - Node.js azure-storage TableService 没有方法

javascript - 找不到模块 : Error: Can't resolve 'crypto'