我试图使用Express创建一个webservice,它将从localhost以及使用Claudia的AWS Lambda中执行。
我想将应用程序配置和 app.listen 功能。
我的 app.ts 文件是这样的。
import express = require('express');
const dotenv = require('dotenv');
class App {
public app: express.Application = express();
constructor() {
dotenv.config();
// parse application/json request body to JSON Objects
this.app.use(express.json());
// parse x-ww-form-urlencoded request body to JSON Objects
this.app.use(express.urlencoded({ extended: true }));
this.app.get('/', (req, res) => {
res.send('API server is up and running');
});
}
}
module.exports = new App().app
然后,我要求应用程序在 本地.ts 文件
const app = require('./app');
app.listen(process.env.PORT,
() => console.log(`Application is running on port ${process.env.PORT}`)
);
我的 软件包.json 样子
{
"name": "nodejs-express-lambda",
"version": "1.0.0",
"description": "",
"main": "app.ts",
"scripts": {
"run": "npx ts-node local.ts",
"build": "tsc"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/dotenv": "^8.2.0",
"dotenv": "^8.2.0",
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.6",
"@types/node": "^14.0.1",
"claudia": "^5.12.0",
"ts-node": "^8.10.1",
"tslint": "^6.1.2",
"typescript": "^3.9.2"
}
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES6"
},
"exclude": [
"node_modules",
]
}
最后,运行 npm run-script run
将返回
app.listen不是一个函数
应用程序在端口3000上运行
我试过了 import app = require('./app')
但也没有用。我对所有这些导出和导入有点迷茫,有人能帮忙吗?
运行 app.listen 从 app.ts 工作正常。
我不知道这是否会有帮助,但你可能想试试这个。
import express from 'express'
import dotenv from 'dotenv' // or just import 'dotenv/config'
class App {
public app: express.Application = express();
constructor() {
dotenv.config();
// parse application/json request body to JSON Objects
this.app.use(express.json());
// parse x-ww-form-urlencoded request body to JSON Objects
this.app.use(express.urlencoded({ extended: true }));
this.app.get('/', (req, res) => {
res.send('API server is up and running');
});
}
}
const app = new App().app
export default app
并在第二个文件中
import app from './app'