Cannot get "/tinder/cards" route but getting "/" route - javascript

This below code is my first react application. After running server.js. After entering "http://localhost:8001/" I got HELLO!!. I expected after entering "http://localhost:8001/tinder/cards" url on chrome and postman too I get following error.
error message: "Cannot GET /tinder/cards".
this is my server.js file.
import mongoose from 'mongoose'
import Cors from 'cors'
import Cards from './dbCards.js'
// App Config
const app = express()
const port = process.env.PORT || 8001
const connection_url = 'mongodb+srv://admin:0tRkopC1DKm4ym4V#cluster0.iw73w.mongodb.net/tinderDB?retryWrites=true&w=majority'
// Middlewares
app.use(express.json())
app.use(Cors())
app.use('/',router);
// DB Config
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
// API Endpoints
app.get("/", (req, res) => res.status(200).send("HELLO!!"))
app.get("/hello", (req, res) => res.status(200).send("Oooooooo!!"))
app.post("/tinder/cards", (req, res) => {
const dbCard = req.body
Cards.create(dbCard, (err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get("/tinder/cards", (req, res) => {
Cards.find((err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
// Listener
app.listen(port, () => console.log(`listening on location: ${port}`)) ```

try this in your app.get('/tinder/cards') section:
// Doing it the Asynchronous way
app.get('/tinder/cards', async (req, res) => {
try { // Trying for getting the cards
const allCards = await Cards.find(); // Getting the cards
res.status(200).send(allCards); // Sending the cards
} catch (error) { // Catching the error
res.status(500).send(error); // Sending the error
}
});

Try to replace cards with card in the URL. Have a look at the image for the same.

Related

Attempting to set up static HTML pages using express

I am trying to set up a few pages so that when a user goes to locahost:number/war . They can see the /war page. But when I run the server I get a "Cannot GET war" error on the page. I've set it up similar to this before and didnt have an issue.
I also get a "ReferenceError: __dirname is not defined" issue on the console
import express from 'express';
const app = express();
const router = express.Router();
import path from 'path';
import {getData} from './server.js'
// HTML Routes
router.get('/', (req,res)=> {
res.sendFile(path.join(__dirname, "../start.html"));
})
router.get('/war', (req,res)=> {
res.sendFile(path.join(__dirname, "../index.html"));
})
router.get('/score', (req,res)=> {
res.sendFile(path.join(__dirname, "../finalScore.html"));
})
// Data
export async function sendStats(){
app.get("/data", (req,res)=> {
const data = getData()
res.json(data)
})
app.post("/data",(req, res) => {
const {name, score} = req.body
const data = createData(name, score)
res.json(data)
} )
app.use((err, req, res, next) => {
console.log(err.stack)
res.status(500).send('Something Broke!')
})
app.listen(7171, ()=> {
console.log('Server is running on port 9191')
})
}
const data = await sendStats();
You forgot to load the router in the app:
app.use('/', router)

NodeJs Rest api: I can make calls in postman but the route returns as not found in url

When I make a post request to the /login endpoint in postman it works fine and returns all the information. However when I try to navigate to the end point in the url the route returns unfound. In the console I get GET http://localhost:5000/login 404 (Not Found). Why is the console returning for a get request? If I try to call the post request in axios I get xhr.js:177 POST http://localhost:3000/login 404 (Not Found).
app.js
require("dotenv").config();
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const router = express.Router();
const cors = require('cors');
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
const mongoose = require('mongoose');
const connection = "password"
mongoose.connect(connection, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
const clientRoutes = require('./routes/clientRoutes');
const traderRoutes = require('./routes/traderRoutes');
const loginRoute = require('./routes/loginRoute')
app.use('/', clientRoutes, traderRoutes, loginRoute);
// setup a friendly greeting for the root route
app.get('/', (req, res) => {
res.json({
message: 'Welcome to the REST API for Pave!',
});
});
// send 404 if no other route matched
app.use((req, res) => {
res.status(404).json({
message: 'Route Not Found',
});
});
// setup a global error handler
app.use((err, req, res, next) => {
if (enableGlobalErrorLogging) {
console.error(`Global error handler: ${JSON.stringify(err.stack)}`);
}
res.status(err.status || 500).json({
message: err.message,
error: {},
});
});
app.listen(5000, () => console.log('Listening on port 5000!'))
loginRoute.js
require("dotenv").config();
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const bcryptjs = require("bcryptjs");
const Client = require("../models/clientSchema");
const Trader = require("../models/traderSchema");
function asyncHandler(callback) {
return async (req, res, next) => {
try {
await callback(req, res, next);
} catch (error) {
next(error);
console.log(error);
}
};
}
router.post('/login', asyncHandler(async (req, res, next) => {
let user = req.body;
const trader = await Trader.findOne({ emailAddress: req.body.emailAddress })
if (user && trader) {
console.log(trader)
let traderAuthenticated = await bcryptjs.compareSync(user.password, trader.password);
console.log(traderAuthenticated)
if (traderAuthenticated) {
console.log('Trader match')
const accessToken = jwt.sign(trader.toJSON(), process.env.ACCESS_TOKEN_SECRET)
res.location('/trader');
res.json({
trader: trader,
accessToken: accessToken
}).end();
} else {
res.status(403).send({ error: 'Login failed: Please try again'}).end();
}
} else if (user && !trader) {
const client = await Client.findOne({emailAddress: req.body.emailAddress})
console.log(client)
let clientAuthenticated = await bcryptjs.compareSync(user.password, client.password);
console.log(clientAuthenticated)
if (clientAuthenticated) {
console.log('Client match')
const accessToken = jwt.sign(client.toJSON(), process.env.ACCESS_TOKEN_SECRET)
res.location('/client');
res.json({
client: client,
accessToken: accessToken
});
} else {
res.status(403).send({ error: 'Login failed: Please try again'}).end();
}
} else {
res.status(403).send({ error: 'Login failed: Please try again'}).end();
}
})
);
module.exports = router;
You set POSTMAN to make a POST request, right? When you enter a url in the browser, that causes a GET request - and you have no route to manage this that I can see, but for the default Not found.
you are calling with axios with wrong port no. it should, POST method http://localhost:5000/login as your application is running on port 5000.
but you are calling, POST http://localhost:3000/login

How can we add collections in mongoDB dynamically( through users)?

Adding collections manually is easy but adding it dynamically giving me unexpected answer.
I am getting a collection name from frontend to backend using promt and axios but when I am doing
const variable_from_frontEnd = mongoose.model(variable_from_frontEnd, Schema);
it is not adding any collections.
import express from "express";
import mongoose from "mongoose";
import Messages from "./messages.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
const pusher = new Pusher({
appId: "1183689",
key: "c9fa659fc6b359a23989",
secret: "9da56a5db535e10c7d95",
cluster: "eu",
useTLS: true
});
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:zoe6B82AZjaLXgw7#cluster0.zp9dc.mongodb.net/Whatsapp_MERN?retryWrites=true&w=majority";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
const groupSchema = mongoose.Schema( {
message: String,
name: String,
timestamp: String,
received: Boolean,
});
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await Messages.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new personalGroup(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// route for creating new collection in mongoDB
app.post("/room/new", async (req, res) => {
try{
let groupName = req.body.room;
groupName = mongoose.model(groupName, groupSchema);
if(!groupName){
console.log("error is occured");
}else{
console.log(groupName);
}
}
catch(err){
res.status(400).send(err);
}
})
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
Let's say I have type a collection name "studyGroup" from frontend then
console is giving me
Model { studyGroup }
Can someone help me why it is happening and how can I add collections manually.

No response from node js (mongoose)

I send request from React with:
export const loadItems = () => async dispatch => {
await axios
.get("http://localhost:8000/api/users")
.then(response => {
console.log(response.users);
dispatch(dataLoaded(response.users));
})
.catch(err => {
dispatch(dataLoadFailed(err));
});
};
But there is no response, and the server does not take request, here is my server app code:
server.js
// a lot of requires
const todoRoutes = require("./routes/serverRoute");
const url = "mongodb://localhost:27017/taskManager";
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect(
url,
{ useNewUrlParser: true },
function(err) {
if (err) {
console.log(err);
} else console.log("Database connected");
}
);
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/public/index.html"));
});
// cors allow
app.use("/api", todoRoutes);
app.listen(8000, () => {
console.log("API started");
});
And this is a controller I use, it's all good with Schema and DB, I checked with output to console from the node, users is defined and contains data
const mongoose = require("mongoose");
const User = require("../models/UserModel");
module.exports = {
getUsers(req, res) {
User.find().exec((err, users) => {
if (err) {
console.log(err);
return res.send({ err });
} else {
console.log(users);
return res.send({ users });
}
});
}
};
And this is my router:
module.exports = router => {
router.get('/users', userController.getUsers);
}
Ok, I got it on my own. Problem was here:
router.get('/users', userController.getUsers);
It supposed to be like this:
router.get('/users', userController.getUsers());

Error when connecting to MongoDB node.js - client is not defined

I cannot seem to connect to my MongoDB. Here is the error that occurs:
RefernceError : Client is not defined .
at MongoClient.connect ( C:/user/User/desktop/blog app.js
at args.push
const express = require('express');
const bodyParser= require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
const MongoClient = require('mongodb').MongoClient
var db
MongoClient.connect('mongodb://user:pass#ds029466.mlab.com:29466/movie-quotes', (err, database) => {
// ... start the server
if (err) return console.log(err)
db = client.db('movie-quotes')
app.listen(process.env.PORT || 3000, () => {
console.log('listening on 3000')
})
})
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
// Note: __dirname is directory that contains the JavaScript source code. Try logging it and see what you get!
// Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.
})
app.post('/quotes', (req, res) => {
db.collection('quotes').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})
database is your database client. You should use:
db = database.db('movie-quotes')
instead of:
db = client.db('movie-quotes')

Categories

Resources