В настоящее время я строю бэкэнд-сервер для электронной коммерции. Все хорошо на сервере Localhost. Но vercel API не работает и не показывает никакой ошибки на консоли.
Когда я переключаю маршрутизатор, подобный https://ecommerce-backend-sand-eight.ve ... p/products not_found, но не выполняется на локальном. />
только показывающая домашнюю страницу
vercel.json
{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "./index.js",
"methods": [
"GET,HEAD,PUT,PATCH,POST,DELETE"
]
}
]
}
package.json
{
"name": "ecommerce-backend",
"version": "2.2.0",
"main": "index.js",
"engines": {
"node": "18.x"
},
"scripts": {
"dev": "nodemon index.js",
"start": "node index.js",
"build": "netlify deploy --prod",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Md Yousuf",
"license": "ISC",
"description": "Ecommerce server app",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"ejs": "^3.1.6",
"express": "^4.21.2",
"http": "^0.0.1-security",
"mongodb": "^6.13.1",
"multer": "^1.4.5-lts.1",
"netlify-cli": "^20.0.2",
"netlify-lambda": "^2.0.16",
"nodemon": "^3.1.0",
"serverless-http": "^3.2.0"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}
index.js
const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion } = require('mongodb');
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');
dotenv.config();
const app = express();
const port = process.env.PORT || 5000;
// Enable CORS
app.use(cors({
origin: '*',
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
preflightContinue: false,
optionsSuccessStatus: 204
}));
// Parse JSON bodies
app.use(express.json());
// Ensure 'uploads' directory exists and serve it statically
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
app.use('/uploads', express.static(uploadDir));
// Serve public assets
app.use(express.static(path.join(__dirname, 'public')));
// Environment validation
const uri = process.env.NEW_URL;
if (!uri) {
console.error('Error: Missing MongoDB connection string (NEW_URL) in .env');
process.exit(1);
}
// MongoDB client
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
async function startServer() {
try {
// Connect to MongoDB
await client.connect();
console.log('Successfully connected to MongoDB');
const db = client.db('insertDB');
// Register routes with injected database
app.use('/products', require('./routes/products')(db));
app.use('/orders', require('./routes/orders')(db));
app.use('/sliders', require('./routes/sliders')(db));
app.use('/categories', require('./routes/categories')(db));
// Home route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'home.html'));
});
// Start listening
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
}
startServer();
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('\nGracefully shutting down');
await client.close();
process.exit(0);
});
routes\categories.js
const express = require("express");
const { ObjectId } = require("mongodb");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const router = express.Router();
// -------------------
// Multer Configuration
// -------------------
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/");
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, uniqueSuffix + path.extname(file.originalname));
},
});
// File filter for images only
const fileFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image/")) {
cb(null, true);
} else {
cb(new Error("Only image files are allowed!"), false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
});
// -------------------
// End of Multer Config
// -------------------
module.exports = (database) => {
const categoriesCollection = database.collection("categories");
// Get all categories
router.get("/", async (req, res) => {
try {
const categories = await categoriesCollection.find({}).toArray();
res.json(categories);
} catch (error) {
res.status(500).json({ error: "Failed to fetch categories" });
}
});
// Create a new category
router.post("/", upload.single("image"), async (req, res) => {
try {
const newCategory = {
name: req.body.name,
slug: req.body.slug,
description: req.body.description,
image: req.file ? `/uploads/${req.file.filename}` : null,
createdAt: new Date(),
updatedAt: new Date(),
};
const result = await categoriesCollection.insertOne(newCategory);
// Fetch the newly inserted category
const insertedCategory = await categoriesCollection.findOne({
_id: result.insertedId,
});
res.status(201).json(insertedCategory);
} catch (error) {
res.status(400).json({ error: "Category creation failed" });
}
});
// Update an existing category
router.put("/:id", upload.single("image"), async (req, res) => {
try {
const updateData = {
...req.body,
updatedAt: new Date(),
};
if (req.file) {
updateData.image = `/uploads/${req.file.filename}`;
}
const result = await categoriesCollection.updateOne(
{ _id: new ObjectId(req.params.id) },
{ $set: updateData }
);
if (result.modifiedCount === 0) {
return res.status(404).json({ error: "Category not found" });
}
// Fetch the updated category
const updatedCategory = await categoriesCollection.findOne({
_id: new ObjectId(req.params.id),
});
res.json(updatedCategory);
} catch (error) {
res.status(400).json({ error: "Update failed" });
}
});
// Delete a category
router.delete("/:id", async (req, res) => {
try {
const result = await categoriesCollection.deleteOne({
_id: new ObjectId(req.params.id),
});
if (result.deletedCount === 0) {
return res.status(404).json({ error: "Category not found" });
}
res.json({ message: "Category deleted successfully" });
} catch (error) {
res.status(400).json({ error: "Deletion failed" });
}
});
return router;
};
Подробнее здесь: https://stackoverflow.com/questions/795 ... app-api-no
Сервер Nodejs, работающий на Localhost должным образом, но проблема - это API приложения Vercel, не работает какими -либ ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Бэкэнд -сервер работает над LocalHost, но не над приложением Vercel
Anonymous » » в форуме Javascript - 0 Ответы
- 7 Просмотры
-
Последнее сообщение Anonymous
-