I am encountering this error
POST http://localhost:4000/api/product/validate-coupon 404 (Not Found)
while accessing the validate-coupon in the front end this is how I am accessing the endpoint in the front end
import React, { useContext, useState } from 'react';
import { ShopContext } from '../context/ShopContext';
import axios from 'axios';
import { toast } from 'react-toastify';
const CartTotal = () => {
const { currency, delivery_fee, getCartAmount,} = useContext(ShopContext);
const backendUrl = import.meta.env.VITE_BACKEND_URL
const [couponCode, setCouponCode] = useState(''); // To store the coupon code
const [discountAmount, setDiscountAmount] = useState(0); // To store the discount amount in numeric form
const [couponApplied, setCouponApplied] = useState(false); // Track whether the coupon is applied or not
// Apply Coupon Logic
const applyCoupon = async () => {
try {
const response = await axios.post(
backendUrl + '/api/product/validate-coupon',
{ couponCode },
{ headers: { token: 'dummy-token'} }
);
if (response.data.success) {
const discount = response.data.coupon.discountOption;
const discountValue = (getCartAmount() + delivery_fee) * (discount / 100);
setDiscountAmount(discountValue);
setCouponApplied(true);
toast.success(`Coupon Applied: -${currency} ${discountValue.toFixed(2)}`);
} else {
setDiscountAmount(0);
setCouponApplied(false);
toast.error('Invalid Coupon Code');
}
} catch (error) {
setDiscountAmount(0);
setCouponApplied(false);
toast.error('An error occurred while applying the coupon');
}
};
const totalAmount = (getCartAmount() + delivery_fee) - discountAmount;
return (
<div className='w-full'>
<div className='flex justify-between'>
<input
type="text"
placeholder="Enter Coupon Code"
value={couponCode}
onChange={(e) => setCouponCode(e.target.value)}
className="border border-gray-300 rounded py-1.5 px-3.5 w-full"
/>
<button
type="button"
onClick={applyCoupon}
className="ml-3 text-blue-600 mt-2"
>
Apply Coupon
</button>
</div>
<hr />
{couponApplied && (
<div className='flex justify-between'>
<p>Discount Applied</p>
<p>-{currency} {discountAmount.toFixed(2)}</p>
</div>
)}
<hr />
<div className='flex justify-between'>
<b>Total</b>
<b>{currency} {totalAmount === 0 ? 0 : totalAmount.toFixed(2)}</b>
</div>
</div>
);
};
export default CartTotal;
and this is the controller which include the validate-coupon function
import { v2 as cloudinary } from "cloudinary";
import productModel from "../models/productModel.js";
const validateCoupon = async (req, res) => {
try {
const { couponCode } = req.body;
// Check if the coupon code exists in your products
const product = await productModel.findOne({ couponCode });
if (product) {
// If coupon code is valid, return the discount value (percentage)
res.json({
success: true,
coupon: {
couponCode: product.couponCode,
discountOption: product.discount // Assuming it's a percentage discount
}
});
} else {
// If coupon code is not found, return an error message
res.json({ success: false, message: "Invalid coupon code!" });
}
} catch (error) {
console.log(error);
console.error('Coupon validation error:', error);
res.json({ success: false, message: error.message });
}
};
export { validateCoupon };
this is how my product route looks like
import express from 'express';
import { listProducts, addProduct, removeProduct, singleProduct, validateCoupon } from '../controllers/productController.js';
import upload from '../middleware/multer.js';
const productRouter = express.Router();
productRouter.post('/validate-coupon', validateCoupon);
export default productRouter;
and the server.js
import express from 'express'
import cors from 'cors'
import 'dotenv/config'
import connectDB from './config/mongodb.js'
import connectCloudinary from './config/cloudinary.js'
import userRouter from './routes/userRoute.js'
import productRouter from './routes/productRoute.js'
// App Config
const app = express()
const port = process.env.PORT || 4000
connectDB()
connectCloudinary()
// middlewares
app.use(express.json())
app.use(cors())
// api endpoints
app.use('/api/product', productRouter)
app.get('/', (req, res) => {
res.send("API Working")
})
app.listen(port, () => console.log('Server started on PORT : ' + port))
I have tried changing the endpoint syntax but don't know why I am encountering these erorrs.
MCVE:
import express from 'express';
const app = express();
const port = process.env.PORT || 4000;
const productRouter = express.Router();
productRouter.post('/validate-coupon', (req, res) => {
console.log('/validate-coupon');
res.send();
});
app.use('/api/product', productRouter);
app.get('/', (req, res) => {
res.send('API Working');
});
app.listen(port, () => console.log('Server started on PORT : ' + port));