When I am trying to give post request to "http://localhost:4000/api/v1/product/new" url I am getting this error "Error: connect ECONNREFUSED 127.0.0.1:4000". My json text:
{
"name": "product",
"description": "this is a sample product",
"price": 30000,
"category": "Laptop",
"images":{
"public_id": "sample image",
"url": "sampleUrl"
}
}
My server.js:
const app = require("./app");
const dotenv = require("dotenv");
const connectDatabase = require("./config/database");
//config
dotenv.config({ path: "backend/config/config.env" });
//connecting to database
connectDatabase();
app.listen(process.env.PORT, () => {
console.log(`Server is running on http://localhost:${process.env.PORT}`);
});
My controller file productController.js:
const Product = require("../models/productModel");
// Create Product
exports.createproduct = async (req, res, next) => {
const product = await Product.create(req.body);
res.status(201).json({
success: true,
product,
});
};
exports.getAllProducts = (req, res) => {
res.status(200).json({ message: "Route is working fine" });
};
My route file productRoute.js :
const express = require("express");
const {
getAllProducts,
createproduct,
} = require("../controllers/productController");
const router = express.Router();
router.route("/products").get(getAllProducts);
router.route("/product/new").post(createproduct);
module.exports = router;
And lastly my model file productModel.js is:
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please Enter product Name"],
trim: true,
},
description: {
type: String,
required: [true, "Please Enter product Description"],
},
price: {
type: Number,
required: [true, "Please Enter product Price"],
maxLength: [8, "Price cannot exceed 8 characters"],
},
ratings: {
type: Number,
default: 0,
},
images: [
{
public_id: {
type: String,
required: true,
},
url: {
type: String,
required: true,
},
},
],
category: {
type: String,
required: [true, "Please Enter Product Category"],
},
Stock: {
type: Number,
required: [true, "Please Enter product Stock"],
maxLength: [4, "Stock cannot exceed 4 characters"],
default: 1,
},
numOfReviews: {
type: Number,
default: 0,
},
reviews: [
{
name: {
type: String,
required: true,
},
rating: {
type: Number,
required: true,
},
comment: {
type: String,
required: true,
},
},
],
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Product", productSchema);
And my config.env file is:
PORT = 4000
DB_URI = "mongodb://0.0.0.0:27017/Ecommerce"
I also tried, by adding "app.use(bodyParser.urlEncoded({extended:false}))" and cors but still it didn't working.