我使用 Node.js、Express 和 MongoDB 构建了一个后端应用程序,并尝试使用无服务器框架将其部署在 AWS 上。该应用程序在我的本地环境中运行良好,但是当我将其部署到 AWS 并尝试使用 Postman 调用 API 时,我收到 500 内部服务器错误。
设置详情: • 框架:无服务器框架 • 环境:AWS Lambda(Node.js 运行时) • API 结构: • 使用 Express 作为 Web 框架 • 路由包括/api/v1/users/login、/api/v1/videos 等。 • 启用 CORS • 实施错误处理
遇到错误: 当我向 API 端点发送请求时,我收到以下响应:
{ "message": "Internal Server Error" }
代码片段:
这是我的
src/index.js
:
import dotenv from "dotenv";
import connectDB from "./db/index.js";
import { app } from "./app.js";
import serverless from "serverless-http";
dotenv.config({
path: "./.env",
});
connectDB()
.then(() => {
app.on("error", (error) => {
console.log("ERROR: ", error);
throw error;
});
app.listen(process.env.PORT || 8000, () => {
console.log(`Server is running at port: ${process.env.PORT}`);
});
})
.catch((error) => {
console.log("MONGODB connection failed !!! ", error);
});
export const handler = serverless(app);
这是我的
src/app.js
:
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
const app = express();
app.use(
cors({
origin: process.env.CORS_ORIGIN,
credentials: true,
})
);
// setting for handling json
app.use(
express.json({
limit: "16kb",
})
);
//setting for URLS
app.use(
express.urlencoded({
extended: true,
limit: "16kb",
})
);
app.use(express.static("public"));
//config cookie-parse
app.use(cookieParser());
// routes import
import userRouter from "./routes/users.routes.js";
import videoRouter from "./routes/video.routes.js";
import commentRouter from "./routes/comment.routes.js";
import likeRouter from "./routes/like.routes.js";
import tweetRouter from "./routes/tweet.routes.js";
import subscriptionRouter from "./routes/subscription.routes.js";
import playlistRouter from "./routes/playlist.routes.js";
import dashboardRouter from "./routes/dashboard.routes.js";
import { ApiError } from "./utils/ApiError.js";
//routes declaration
app.use("/api/v1/users", userRouter);
app.use("/api/v1/videos", videoRouter);
app.use("/api/v1/comments", commentRouter);
app.use("/api/v1/likes", likeRouter);
app.use("/api/v1/tweets", tweetRouter);
app.use("/api/v1/subscription", subscriptionRouter);
app.use("/api/v1/dashboard", dashboardRouter);
app.use("/api/v1/playlist", playlistRouter);
app.use((err, req, res, next) => {
if (err instanceof ApiError) {
// Send a JSON response with the error details
return res.status(err.statusCode).json({
success: err.success,
message: err.message,
errors: err.errors,
});
}
// For other errors, send a generic 500 response
// res.status(500).json({
// success: false,
// message: "An unexpected error occurred.",
// });
});
export { app };
这是我的
serverless.yml
:
service: playtube-api
provider:
name: aws
runtime: nodejs20.x
region: ap-south-1
environment:
PORT: ${env:PORT}
CORS_ORIGIN: ${env:CORS_ORIGIN}
MONGODB_URI: ${env:MONGODB_URI}
ACCESS_TOKEN_SECRET: ${env:ACCESS_TOKEN_SECRET}
ACCESS_TOKEN_EXPIRY: ${env:ACCESS_TOKEN_EXPIRY}
REFRESH_TOKEN_SECRET: ${env:REFRESH_TOKEN_SECRET}
REFRESH_TOKEN_EXPIRY: ${env:REFRESH_TOKEN_EXPIRY}
CLOUDINARY_CLOUD_NAME: ${env:CLOUDINARY_CLOUD_NAME}
CLOUDINARY_API_KEY: ${env:CLOUDINARY_API_KEY}
CLOUDINARY_API_SECRET: ${env:CLOUDINARY_API_SECRET}
CLOUDINARY_URL: ${env:CLOUDINARY_URL}
functions:
api:
handler: src/index.handler
events:
- httpApi:
path: /{proxy+}
method: ANY
plugins:
- serverless-dotenv-plugin
这是我第一次使用它并部署后端服务器请帮助我,我将不胜感激。
除非您使用本地或AWS EC2等环境,否则您不需要监听端口。
import dotenv from "dotenv";
import connectDB from "./db/index.js";
import { app } from "./app.js";
import serverless from "serverless-http";
dotenv.config({
path: "./.env",
});
connectDB()
.catch((error) => {
console.log("MONGODB connection failed !!! ", error);
});
export const handler = serverless(app);
此外,
app.on('error')
在express中不起作用,app.use((err, req, res, next)
足以捕获错误。