Can not call API from backend mongodb - node.js

I'm trying to call my mongoDB API but it's giving me this error:
xhr.js:178 GET http://localhost:3000/api/products 404 (Not Found)
Here is how I call my API:
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const res = await axios.get("/api/products");
setProducts(res.data);
setLoading(false);
console.log(res.data)
};
document.title = `Shop - The Beuter`;
fetchItems();
}, [props]);
And here is my server.js:
const express = require("express"),
bodyParser = require('body-parser'),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
this is my database.config.js:
const mongoose = require("mongoose");
module.exports = (name) => {
mongoose
.connect(process.env.MONGODB_URI || `mongodb://localhost/${name}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log(`Successfully connected to ${name}`))
.catch((err) => console.log(err));
};
How can I fix this problem?
Here is my github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter

Related

Mongo DB didn't connect with my node server

I'm new in node and mongo.
I'm trying to connect mongo db with my node server but this error appears.
Error:getaddrinfo ENOTFOUND locahost
[nodemon] app crashed - waiting for file changes before starting...
server.js
`const express = require('express');
require('colors');
const products = require('./data/products');
const dotenv = require('dotenv');
//dotenv config
dotenv.config();
const { connectDb } = require('./config/config')
connectDb();
const app = express();
app.get('/', (req, res) => {
res.send('<h1>Welcome to Node server</h1>')
})
app.get('/products', (req, res) => {
res.json(products);
})
app.get('/products/:id', (req, res) => {
const product = products.find(p => p.id === req.params.id);
res.json(product);
})
const PORT = 8080;
app.listen(process.env.PORT || PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${process.env.PORT}`.inverse.green)
})`
config.js
const mongoose = require('mongoose');
require('colors');
const connectDb = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
})
console.log(`MongoDB connected ${conn.connection.host}`.yellow)
} catch (error) {
console.error(`Error:${error.message}`.inverse.red);
process.exit(1);
}
};
module.exports = { connectDb }
.env
PORT = 8080
NODE_ENV = development
MONGO_URI = mongodb://locahost:27017/local

how can i convert a JSON object into an XML file with nodejs?

I can't find documentation that can help me or some examples.
I created a model (json object) for my data base (mongodb) then I created a form in the client side (react) to generate my data. I want to know how can I take this data and convert it into an XML file. All I know is JSon object can be converted in xml file I tried some things but they don't work.
This my model:
const mongoose = require('mongoose');
const fileSchema = mongoose.Schema({
title: {
type: String,
trim: true
},
file_path: {
type: String,
required: true
},
file_mimetype: {
type: String,
required: true
}
}, {
timestamps: true
});
const File = mongoose.model('File', fileSchema);
module.exports = File;
and this is my server.js
require("dotenv").config({ path: "./config.env" });
const express = require("express");
const app = express();
const errorHandler = require("./middleware/error");
const path = require('path');
const fileRoute = require('./routes/file');
const Cors = require('Cors');
const mongoose = require('mongoose')
require('dotenv').config();
app.use(Cors());
// Connect DB
const PORT = process.env.PORT || 5000;
const url = process.env.MONGO_URL;
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => {
console.log("Server up and running!")
})
app.use(express.json());
app.get("/", (req, res, next) => {
res.send("Api running");
});
// Connecting Routes
app.use("/api/auth", require("./routes/auth"));
app.use("/api/private", require("./routes/private"));
//aploadfile
app.use(express.static(path.join(__dirname, '..', 'build')));
app.use(fileRoute);
app.get("/upload", (req, res) => {
res.sendFile(path.join(__dirname, '..', 'build', 'index.html'));
});
// Error Handler Middleware
app.use(errorHandler);
const server = app.listen(PORT, () =>
console.log(`Sever running on port ${PORT}`)
);
process.on("unhandledRejection", (err, promise) => {
console.log(`Logged Error: ${err.message}`);
server.close(() => process.exit(1));
});

connectDB is not a function

Hi I'm new to coding currently trying to set up a connection to my server.
Getting an error message:
"TypeError: connectDB is not a function"
This is my db.js file
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
and this is my server.js file
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
Looking for some assistance I'm really new to coding so please forgive me if I posted wrongly.
check this out:
You are exporting mongoose from the db.js file. Try exporting the function connectDB you just created.
// between brackets just in case you need to export something else, ok?
module.exports = { connectDB }
Then import it like this:
const { connectDB } = require('./config/db')
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
const express = require('express')
const server = express()
const dotenv = require('dotenv')
const { connectDB } = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)

How to fix routes in node js not working?

Anyone can help me I am new to node js and I am stuck with this error it return 404 not found when I am trying to visit http://localhost:5000/api/items on my postman..
this is the file items.js
const express = require('express');
const router = express.Router();
//Items Model
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({date: -1})
.then(items => res.json(items))
});
router.post('/', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save().then(item => res.json(item));
});
module.exports = router;
this is the server.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
add a '/' before pathname in server.js
app.use('/api/items', items);
localhost:5000/api/items should work then
You need to make the following changes to your server.js
import your router module
const express = require('express');
const mongoose = require('mongoose');
const router = require('path of the router module');
const app = express();
app.use(express.json());
app.use(router); //to use your router
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('/api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
Try this:-
As I can see in the image of "vscode"
you have used router.get("/")
whereas in postman you are using URL for GET request as localhost:5000/api/items.
Either change your backend code to router.get("/api/items") or correct your postman request to localhost:5000/

Cannot retrieve Users data from database. Server doesnt respond

I am learning a MERN stack course on Udemy and currently I am trying to retrieve the user's data from the server but I can't. I am able to retrieve the post data but the connections times out for users data. Can you guys help me find out what went wrong? Thank you in advance!
userController snippet:
exports.allUsers = (req, res) => {
const users = User.find({})
.then((users) => {
console.log(users);
})
.catch(err => console.log(err));
};
User routes snippet
const express = require('express'),
router = express.Router(),
{userById, allUsers } = require('../controllers/userController');
router.get('/users', allUsers);
router.param('userID', userById)
module.exports = router;
app.js code snippet
const express = require('express'),
app = express(),
postRoutes = require('./routes/post'),
authRoutes = require('./routes/auth'),
morgan = require("morgan"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
userRoutes = require('./routes/user'),
expressValidator = require('express-validator');
require('dotenv').config();
mongoose.connect(process.env.MONGO_URI,
{ useUnifiedTopology: true, useNewUrlParser: true })
.then(() => console.log("DB connected"));
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressValidator());
app.use('/', postRoutes);
app.use('/', authRoutes);
app.use('/', userRoutes);
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).json({error: "Unauthorised"});
}
});
app.listen(process.env.PORT || 3000, () => {
console.log(`SERVER AT PORT: 3000`);
});
Postman gets stuck here:
You have to end the request / respond to the request . In your userController you are missing ending/responding the request. You are just logging the user result .
Try this :
exports.allUsers = (req, res) => {
const users = User.find({})
.then((users) => {
console.log(users);
res.status(200).json(users);
})
.catch((err) => {
console.log(err);
res.status(500).json(err.message);
});
}

Resources