Heroku routing does not work
here is my code,
when I deploy my local machine work The Heroku route does not work.
The home route is work but never works on the remote Heroku deployment route
I try to find my problem
tell me what to do
This indicates that the page exists but is producing some sort of error.. Any idea what could be happening? This is a very basic app that I built by reading the Rails Tutorial Book.
import express from "express"
import { MongoClient, ServerApiVersion } from "mongodb"
import { ObjectId } from "mongodb"
import cors from "cors"
import "dotenv/config"
const app = express()
app.use(cors())
app.use(express.json())
const PORT = process.env.PORT || 5000
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#laptopstock.xnbrc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority&ssl=true`
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
})
async function run() {
try {
await client.connect()
const laptopCollection = client.db("laptop_stock").collection("laptops")
app.post("/product", async (req, res) => {
const products = req.body
// console.log(products)
const NewProducts = await laptopCollection.insertOne(products)
res.send(products)
})
// get products
app.get("/product", async (req, res) => {
const query = {}
const cursor = laptopCollection.find(query)
const loadData = await cursor.toArray()
// console.log(loadData)
res.send(loadData)
})
app.get("/product/:id", async (req, res) => {
const id = req.params.id
const query = { _id: ObjectId(id) }
const service = await laptopCollection.findOne(query)
res.send(service)
})
app.put("/update/:id", async (req, res) => {
const id = req.params.id
const data = req.body
const filter = { _id: ObjectId(id) }
const options = { upsert: true }
const updateDoc = {
$set: {
productName: data.productName,
productQuantity: data.productQuantity,
productImg: data.productImg,
productDescription: data.productDescription,
productSeller: data.productSeller,
},
}
const updateProduct = await laptopCollection.updateOne(
filter,
updateDoc,
options,
)
res.send(updateProduct)
})
app.delete("/product/:id", async (req, res) => {
const id = req.params.id
const query = { _id: ObjectId(id) }
const deleteLaptop = await laptopCollection.deleteOne(query)
res.send(deleteLaptop)
})
} catch (error) {
console.log({ massage: error })
}
}
app.get("/", (req, res) => {
res.send({ message: "success" })
})
run()
app.listen(PORT, () => {
console.log("server is running port", PORT)
})
Related
I've been struggling to make the usersRoute work. I keep getting the error message: "Request failed with status code 404" name: "AxiosError", get request is working but post not - Cannot POST /api/users/register. Could you help me figure this out, please? Thank you
usersRoute code is this:
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
router.post("/login", async(req, res) => {
const {username , password} = req.body
try {
const user = await User.findOne({username , password})
if(user){
res.send(user)
}
else{
return res.status(400).json(error);
}
} catch (error) {
return res.status(400).json(error);
}
});
router.post("/register", async(req, res) => {
try {
const newuser = new User(req.body)
await newuser.save()
res.send('Korisnik uspešno registrovan')
} catch (error) {
return res.status(400).json(error);
}
});
module.exports = router
userAction:
import axios from 'axios'
import {message} from 'antd'
export const userLogin=(reqObj)=>async dispatch=>{
dispatch({type: 'LOADING', payload:true})
try {
const response = await axios.post('/api/users/login', reqObj)
localStorage.setItem('user', JSON.stringify(response.data) )
message.success('Prijava uspela')
dispatch({type: 'LOADING', payload:false})
setTimeout(() => {
window.location.href='/'
}, 500);
} catch(error) {
console.log(error)
message.error('Pokušajte ponovo')
dispatch({type: 'LOADING', payload:false})
}
}
export const userRegister=(reqObj)=> async dispatch =>{
dispatch({type: 'LOADING', payload:true})
try {
const response = await axios.post('/api/users/register' , reqObj)
message.success('Registracija uspela')
setTimeout(() => {
window.location.href='/login'
}, 500);
window.location.href='/login'
dispatch({type: 'LOADING', payload:false})
} catch(error) {
console.log(error)
message.error('Pokušajte ponovo')
dispatch({type: 'LOADING', payload:false})
}
}
server.js:
const express = require('express')
const app = express()
const port = process.env.PORT || 5000
const dbConnection = require('./db')
app.use(express.json())
app.use('/api/cars/', require('./routes/carsRoutes'))
app.use('/api/users/', require('./routes/usersRoute'))
app.get('/', (req,res) => res.send('Hello World'))
app.listen(port, () => console.log(`Node JS Server Started in Post ${port}`))
userModel:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
username : {type:String , required : true},
password : {type:String , required : true}
})
const userModel = mongoose.model('users' , userSchema)
module.exports = userModel
package.json:
"proxy": "http://localhost:5000/"
Been following trying to get a mongoose server setup, and it briefly worked, but now it's not for some reason and I honestly have no idea what's going on. No matter what I do, it's returning a blank []?
Collection is "users" all lowercase. Config is in other files. Like I said it has worked before for me briefly and I have no clue why it suddenly stopped.
EDIT - The user object is undefined so it's not even pulling the data from the db for some reason?
server.js
const express = require('express')
const cors = require('cors')
const app = express()
var corsOptions = {
origin: "http://localhost:8080"
}
app.use(cors(corsOptions))
app.use(express.json())
app.use(express.urlencoded({extended:true}))
const db = require('./app/models')
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
app.get("/", (req, res) => {
res.json({ message: "Welcome to server." });
});
require("./app/routes/user.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
model
module.exports = mongoose => {
var schema = mongoose.Schema(
{
id: Number,
ref: String,
name: String,
achieves: Array,
total: Number
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("users", schema);
return User;
};
findAll method in controller
exports.findAll = (req, res) => {
const name = req.query.name;
var condition = name ? { name: { $regex: new RegExp(name), $options: "i" } } : {};
User.find(condition)
.then(data => {
res.send(data);
console.log(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving users."
});
});
};
Try this one at query:
{name: {$regex : `.*${name}.*`, $options: "i"}}
const express = require('express')
const Task = require('../models/task-model')
const auth = require('../middleware/auth')
const router = new express.Router()
router.post('/tasks', auth, async (req, res) => {
const task = new Task({
...req.body,
owner: req.user._id
})
try {
await task.save()
res.status(201).send(task)
}
catch (error) {
res.status(400).send(error)
}
})
router.get('/tasks/count', auth, async (req, res) => {
try {
const count = await Task.countDocuments({})
if (!count) {
res.send(404).send()
}
res.send(count)
}
catch (error) {
res.status(500).send(error)
}
})
module.exports = router
Every route except count is working.
I have tried count() function, but it is deprecated.
Now I am using countDocuments({}) but it gives 500 response.
I have tried estimatedDocumentCount() but same response.
i'm new learner in backend node js ... in my code below i created an API for questions and it contains get,post,delete and edit
i wanted to test it using the extension rest client in VS code but when i type Get http://localhost:3000/api in route.rest file to test it,it stucks on waiting
is there a way to know if my API works good and can somebody please help me if i have mistake below?
thanks in advance
//server.js
// #ts-nocheck
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const questionRoutes = require('./routes/subscribers');
const cors = require('cors');
const http = require('http');
// Has to be move but later
const multer = require("multer");
const Question = require('./models/subscriber');
// express app
const app = express();
// Explicitly accessing server
const server = http.createServer(app);
// corsfffffffff
app.use(cors());
dotenv.config();
const dbURI = process.env.MONGO_URL || "mongodb://localhost:27017/YourDB";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => server.listen(process.env.PORT || 3000) )
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
app.use(express.json);
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// routes
// question routes
app.use('/questions' , questionRoutes );
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
//questionRoute.js
const express = require('express');
const questionController = require('../controllers/questionCon');
const questionApiController = require('../controllers/questionApiController');
const router = express.Router();
// API Routing
router.get('/api/', questionApiController.get_questions);
router.post('/api/add', questionApiController.create_question);
router.get('/api/:id', questionApiController.get_question);
router.delete('/api/delete/:id', questionApiController.delete_question);
router.put('/api/update/:id', questionApiController.update_question);
// EJS Routing for GUI
router.get('/create', questionController.question_create_get);
router.get('/', questionController.question_index);
router.post('/', questionController.question_create_post);
router.get('/:id', questionController.question_details);
router.delete('/:id', questionController.question_delete);
module.exports = router;
//question.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const questionSchema = new Schema({
questionTitle: {
type: String,
required: true,
},
description: {
type: String,
},
price: {
type: Number,
},
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
//questionAPIcontroller
const Question = require('../models/subscriber');
const validators = require('../validators');
let questionApiController = {
// Get a single question
get_question : async (req , res) => {
const id = req.params.id;
try {
const question = await Question.findById(id,(err, question) => {
if (err) return res.status(400).json({response : err});
res.send("hello")
res.status(200).json({response : question})
console.log("hello")
})
} catch (err) {
res.status(400).json(err);
}
},
// Get all the questions
get_questions: async (req , res) => {
try {
const questions = await Question.find((err, questions) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : questions})
})
} catch (err) {
res.status(400).json(err);
}
},
// Create a question
create_question : async (req , res) => {
const {error} = validators.postQuestionValidation(req.body);
if(error) return res.status(400).json({ "response" : error.details[0].message})
try {
const question = await new Question(req.body);
question.save((err, question) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : " Question created Successfully"})
});
} catch (err) {
res.status(400).json(err);
}
},
// Delete question
delete_question : async (req , res) => {
const id = req.params.id;
var questionExist = false;
var userId ;
const question = await Question.findById(id).then(result => {
questionExist = true;
userId = result.owner;
}).catch(err => {
questionExist = false;
res.status(400).json({response : err });
});
if(questionExist){
try {
Question.findByIdAndRemove(id ,(err, question) => {
// As always, handle any potential errors:
if (err) return res.json({response : err});
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Question successfully deleted",
id: question._id
};
return res.status(200).json({response : response });
});
} catch (err) {
res.status(400).json(err);
}
}
else {
return res.status(400).send( { "response" : "A question with that id was not find."});
}
},
// Update question
update_question : async (req , res) => {
const id = req.params.id;
Question.findByIdAndUpdate(id,req.body,
function(err, result) {
if (err) {
res.status(400).json({response : err});
} else {
res.status(200).json({response : "Question Updated"});
console.log(result);
}
})
},
// Get question's questions
}
module.exports = questionApiController
//questionController
const Question = require('../models/subscriber');
const question_index = (req, res) => {
Question.find().sort({ createdAt: -1 })
.then(result => {
res.render('index', { questions: result, title: 'All questions' });
})
.catch(err => {
console.log(err);
});
}
const question_details = (req, res) => {
const id = req.params.id;
Question.findById(id)
.then(result => {
res.render('details', { question: result, title: 'Question Details' });
})
.catch(err => {
console.log(err);
res.render('404', { title: 'Question not found' });
});
}
const question_create_get = (req, res) => {
res.render('create', { title: 'Create a new question' });
}
const question_create_post = (req, res) => {
const question = new Question(req.body);
question.save()
.then(result => {
res.redirect('/questions');
})
.catch(err => {
console.log(err);
});
}
const question_delete = (req, res) => {
const id = req.params.id;
Question.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/questions' });
})
.catch(err => {
console.log(err);
});
}
module.exports = {
question_index,
question_details,
question_create_get,
question_create_post,
question_delete
}
change code
app.use(express.json);
to
app.use(express.json());
I am making an app that saves and shows books to sell. It's everything ok, but this error began to appear:
GET http://localhost:3000/api/usuarios 404 (Not Found) zone-evergreen.js:2952
This error appears in two files: 'apuntes' and 'usuarios'
Here is the controller's code:
const usu = require('../models/usuario')
const usuarioCtrl = {};
usuarioCtrl.getUsuarios = async (req, res) => {
const usuarios = await usu.find();
res.json(usuarios);
}
usuarioCtrl.createUsuarios = async (req, res) => {
console.log(req.body);
const usuario = new usu({
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha: req.body.fecha,
registro: req.body.registro,
password: req.body.password
});
await usuario.save();
res.json({
'status': 'Usuario Creado'
});
}
usuarioCtrl.getUsuario = async (req, res) => {
const usuarios = await usu.findById(req.params.id);
res.json(usuarios);
}
usuarioCtrl.editUsuario = async (req, res) => {
const { id } = req.params;
const usuario = {
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha: req.body.fecha,
registro: req.body.registro,
password: req.body.password
};
await usu.findByIdAndUpdate(id, { $set: usuario }, { new: true });
res.json({ status: 'Usuario Actualizado' });
};
usuarioCtrl.deleteUsuario = async (req, res) => {
await usu.findByIdAndRemove(req.params.id);
res.json({ status: 'Usuario Borrado' });
}
module.exports = usuarioCtrl;
I'm sure that the index and route's code are right, but I don't know what to do and why this is happening. I have two controllers and two routes files and both have the same logic.
This is my first question in StackOverflow, I thank you for your help. If you need more details about the project, please tell me.
Here's the router:
const express=require('express');
const router1 = express.Router();
const ctrl1=require('../controllers/usuarios.controller');
router1.get('/', ctrl1.getUsuarios );
router1.post('/',ctrl1.createUsuarios);
router1.get('/:id',ctrl1.getUsuario);
router1.put('/:id',ctrl1.editUsuario)
router1.delete('/:id',ctrl1.deleteUsuario);
module.exports=router1;