Бэкэнд -сервер работает над LocalHost, но не над приложением VercelJavascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Бэкэнд -сервер работает над LocalHost, но не над приложением Vercel

Сообщение Anonymous »

Я строю бэкэнд на веб -сайте ecommerce . Моя работа почти закончена, но приложение vercel не работает. Это проект node.js . Мой полный код здесь на [github] [1] .
https://github.com/itsmdyousuf/ecommerce-backend
Эта проблема возникла, когда я использовал маршрутизатор. Я не могу решить это сейчас. {
"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 ... vercel-app
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Javascript»