Postman only showing error message and no request is working - node.js

Hi so I'm new in this domain and I'm working on some big project so here's the issue, i'm trying to run postman changing the requests from get to post etc but it's not working here's the app.js file
const express = require('express')
const cors = require("cors");
require("dotenv").config();
const con= require("./helpers/connection");
const bodyParser = require('body-parser');
const app = express()
const port = 3000
app.use(cors({ origin: '*' }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// parse env variables
app.use(function(req, res, next) {
req.con = con
next()
})
app.use("/", require("./routes/routes"));
// Handling errors
//* Handling not mapped routes
app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
//* Handling thrown or server errors
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
And this is my router file
const express = require("express")
const router = express.Router()
const userController = require("../../controllers/usersController.js")
router.get("/", userController.getUsers)
router.get("/:id", userController.getUserById)
router.post("/create", userController.create)
router.put("/:id", userController.edit)
router.delete("/:id", userController.delete)
module.exports = router
when i go to postman and try any of these request this is what i get
{
"error": {
"message": "Not found"
}
}
Please if anyone has any idea why it's not working do share with me

Related

How to solve this error , module not found?

I'm getting this error , module not found,
Cannot find module 'D:\2022\Full StackProjects\FullStackRegisterLoginPage\server.js'
thank you
Error image
server.js
const express = require("express");
const colors = require("colors");
const dotenv = require("dotenv").config();
const { errorHandler } = require("../Backend/Middleware/errorHandler");
const port = process.env.PORT || 8000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/api/users", require("./Routes/userRoutes"));
app.use(errorHandler);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
userRoutes.js
const express = require("express");
const router = express.Router();
const {
registerUser,
loginUser,
getUser,
} = require("../Controllers/userController");
router.post("/", registerUser);
router.post("/login", loginUser);
router.get("/me", getUser);
module.exports = router;
errorHandler.js
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
next();
};
module.exports = { errorHandler };
package.json
package.json
check this out , i've upload all code on github
github repo link

routing in nodeJs - What could be the reason my routing is not working?

I managed my routing via a few routers, but something went wrong,
when i try to call a functton i get the error:
Error: No default engine was specified and no extension was provided.
I can't understand what could be my problem..
I would be greatfull if soembody can help
my code:
// index.js
const express = require("express");
const router = express.Router();
const userRouter = require("./userRouter");
const qeustionRouter = require("./questionRouter");
const questionToTestRouter = require("./questionToTestRouter");
const testRouter = require("./testRouter");
const subjectRouter = require("./subjectRouter");
/* GET home page. */
router.get("/", function (req, res, next) {
res.render("index", { title: "Express is run" });
});
router.get("/user",userRouter);
router.get("/qeustion",qeustionRouter);
router.get("/questionToTest",questionToTestRouter);
router.get("/test",testRouter);
router.get("/subject",subjectRouter);
module.exports = router;
another router for example:
// userRouter.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
router.post('/signUp', userController.signUp)
router.get('/login', userController.login)
router.delete('/deleteStudent', userController.deleteStudent)
router.delete('/deleteTeacher', userController.deleteTeacher)
router.get('/getAllUsers', userController.getAllUsers)
router.get('/getStudentsByTeacherId/:teacherId', userController.getStudentsByTeacherId)
router.get('/getTeachersByStudentId/:userId', userController.getTeachersByStudentId)
router.post('/updateUser', userController.updateUser)
module.exports = router
// app.js
var express = require("express");
var cors = require("cors")
const mongoose = require('mongoose');
//var path = require("path");
// var favicon = require("serve-favicon");
// var logger = require("morgan");
// var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var routes = require("./routes/index");
var app = express();
// view engine setup
// app.set("views", path.join(__dirname, "views"));
// app.set("view engine", "jade");
// // uncomment after placing your favicon in /public
// // app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(express.static(path.join(__dirname, "public")));
app.use(cors());
app.use("/", routes);
//--------------------------------------
//listen to localhost
app.listen(4000, (req, res) => {
console.log("listening on port 4000");
})
//--------------------------------------
//connect to mongo//
const connectionParams = {
useNewUrlParser: true,
// useCreateIndex: true,
useUnifiedTopology: true
}
mongoose.connect(process.env.DB_CONNECT, connectionParams)
.then(() =>
console.log("connected to mongo"))
.catch((error) =>
console.log("error: " + error))
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: err,
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: {},
});
});
module.exports = app;
I think you need a view engine. I see you are defining "jade" as your view engine but it is commented out and it is not in the index.js
please make sure you installed jade package. You can check this by looking at your package.json file.
npm install jade --save
You need to define jade as your view engine (in the index.js) and your jade files must be stored inside the views folder. Inside index.js file, you can change all router keywords to app
const express = require ("express");
const app = express ();
app.set("view engine","jade")
And delete this: const router = express.Router();
And this folder must be placed at the root of your project (in other words, your index.js file and "views" folder should be at the same level). If you do it in this way, you wont need to define a path route.
I kindly advise you to use "ejs" as your view engine. It is more common than "jade". You can create ejs files easily, just like an html page.
And first start with a single route to test if your express framework is working. You can then gradually add up other routes. And please let me know if this answer helps, otherwise I will delete.

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨‍🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

GET localhost:4200/api 404 (Not Found) after submit data

I download the https://github.com/SinghDigamber/Angular8MeanstackAngularMaterial
and deployed it.
But while I tried to save the data and review the data, i always get the
GET http://localhost:4200/api 404 (Not Found)
add data to db error picture
get data to db error picture
Angular v8.0.0
mongoDB v4.0.10
nodejs v12.2.0
//app.js
let express = require('express'),
path = require('path'),
mongoose = require('mongoose'),
cors = require('cors'),
bodyParser = require('body-parser'),
dataBaseConfig = require('./database/db');
// Connecting mongoDB
mongoose.Promise = global.Promise;
mongoose.connect(dataBaseConfig.db, {
useNewUrlParser: true
}).then(() => {
console.log('Database connected sucessfully ')
},
error => {
console.log('Could not connected to database : ' + error)
}
)
// Set up express js port
const studentRoute = require('./routes/student.route')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cors());
// Setting up static directory
app.use(express.static(path.join(__dirname, 'dist/angular8-meanstack-angular-material')));
// RESTful API root
app.use('/api', studentRoute)
// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log('Connected to port ' + port)
})
// Find 404 and hand over to error handler
app.use((req, res, next) => {
next(createError(404));
});
// Index Route
app.get('/', (req, res) => {
res.send('invaild endpoint');
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/angular8-meanstack-angular-material/index.html'));
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
I think you forgot to export get and post functions for your API routes.
you can create routes like this in studentRoute File.
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
return "Hello World";
})
router.post('/', function (req, res, next) {
return "Hello World";
})
module.exports = router;````

Always returning 500 error

var express = require('express');
var router = express.Router();
router.post("/", function(req, res, next) {
console.log('Yes1');
if(!req.body.username || !req.body.password){
console.log('Yes2');
return res.status(401).json(JSON.stringify({
error: 'Username or Password are not set'
}));
}else{
console.log('Yes3');
return res.status(200).json(JSON.stringify({
data: 'Okay'
}));
}
//error handler
router.use(function(err, req, res, next) {
res.status(500).json(JSON.stringify({
error: err
}));
});
module.exports = router;
From the front end I am sending a username and password. I am expecting to either be receiving errors 200 or 401. For some reason though I receiving error 500 which is the default error handler. I am not sure how it is coming here. On my server console Yes1 and Yes2 are being printed so why am I not getting error 401?
I don't know if you have more code or not, but you need to install your router with app.use('/', router).
You also need to install the body-parser middleware to be able to parse req.body.
Your whole application should look something like this:
// router.js
var express = require('express');
var router = express.Router();
router.post("/", function(req, res, next) {
console.log('Yes1');
console.log(req.body);
if(!req.body.username || !req.body.password){
console.log('Yes2');
return res.status(401).json(JSON.stringify({
error: 'Username or Password are not set'
}));
}else{
console.log('Yes3');
return res.status(200).json(JSON.stringify({
data: 'Okay'
}));
}
});
//error handler
router.use(function(err, req, res, next) {
res.status(500).json(JSON.stringify({
error: err
}));
});
module.exports = router;
// server.js
var express = require('express');
var bodyParser = require('body-parser');
var customRouter = require('./router.js');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use('/', customRouter);
app.listen(3000, function () {
console.log('Listening on port 3000...');
});
See error handling and routing documentation.
It appears that your middleware handler is firing, because 401 is an error, and you are resetting the status to 500.

Resources