process.env.PORT 未定义。在 TypeScript 中发生问题。

huangapple go评论79阅读模式
英文:

process.env.PORT is Undefined. Problem occurring in typescript

问题

我是新手使用 TypeScript。

导入并使用 dotenv 包,但仍然得到 undefined。

是否需要为 dotenv 变量声明接口?

import express, { Application } from 'express';
import bodyParser from 'body-parser';
import dotenv from 'dotenv';
dotenv.config();

const app: Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

console.log(process.env.PORT);   //undefined

app.listen(3000, () => console.log(`服务器已启动在 http://localhost:${3000}`));

.env 文件

PORT = 3000
SECRET = SOME_SECRET

package.json

{
  "dependencies": {
    "body-parser": "^1.20.1",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.4"
  }
}
英文:

I am new to typescript.

Imported and used dotenv package but still getting undefined
It is necessary to declare interface for the dotenv variables?

import express,{Application} from 'express';
import bodyParser from 'body-parser';
import  dotenv from 'dotenv';
dotenv.config();

const app : Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

console.log(process.env.PORT);   //undefined

app.listen(3000, ()=>console.log(`server started on 

http://localhost:${3000}`));

.env File

PORT = 3000
SECRET=SOME_SECRET

package.json

{
  "dependencies": {
    "body-parser": "^1.20.1",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.4"
  },
}

答案1

得分: 1

不需要在Typescript中为环境变量声明接口。你的 .env 文件相对于你粘贴的Typescript文件应该位于项目的根目录,与项目的 package.json 文件位于同一目录下。如果它位于根目录之外的某个位置,或者 dotenv 无法识别它的位置,我建议使用以下示例配置dotenv:

dotenv.config( { path: '../相对路径/.env' });
英文:

You don't have to declare interfaces for environment variables in Typescript. Where's your .env file located relative to the Typescript file you pasted?

The .env file should be at the project's root, in the same directory as the project's package.json file. If it's located somewhere that's not the root or that dotenv can't figure out, I'd recommend using the following example for configuring dotenv:

dotenv.config( { path: '../relative/path/.env' });

huangapple
  • 本文由 发表于 2023年1月7日 23:59:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75041733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定