GET localhost:4200/api 404 (Not Found) after submit data - node.js

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;````

Related

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.

Postman only showing error message and no request is working

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

How can I prevent express-ejs-layouts for wrapping my other page?

I'm finding a page layout for node.js like laravel php have their Template for layout and it is perfect. I want to achieve it here in node.js and finally found this express-ejs-layouts but there is a problem in it that I cant see in their documentation the layout will wrap all of my pages specially my signin and signup page which have a different header and footer. How can we prevent express-ejs-layouts from wrapping my other page?
const express = require('express');
const router = express.Router();
const path = require('path');
const multer = require('multer');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const server = require('http').createServer(app);
const expressLayouts = require('express-ejs-layouts');
// Set Database Connection
const connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'project_101'
});
connection.connect(function(error){
if(!!error) console.log(error);
else console.log('Database Connected!');
});
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressLayouts);
app.get('/',(req, res) => {
let sql = "SELECT * FROM uploads";
let query = connection.query(sql, (err, rows) => {
if(err) throw err;
res.render('index');
});
});
app.get('/signup', (req, res) => {
res.render('signup');
});
app.get('/signin', (req, res) => {
res.render('signin');
});
app.get('/unknown-user', (req, res) => {
res.render('unknown-user');
});
app.get('/profile', (req, res) => {
res.render('profile');
});
const port = process.env.PORT || 3000;
// Server Listening
server.listen(port, function () {
console.log('Server successfully running at: -',port);
});
Finally got the solution for the problem express-ejs-layouts
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
You just need to declare your page as a layout and set it to false.
app.set("layout signin", false);
and render the page together with the layout.
app.get('/signin', (req, res) => {
res.render('signin', { layout: 'signin' });
});
ez fix ⚡️
You can bypass the template by sending the file back.
res.sendFile(path, options, fn);
options and fn are optional.

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}`)
});

post using restler and node.js is not returning

I am trying to post using restler and return the response to client but response never returns .Below is code I am using and response is just hanging
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var rest = require('restler');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3001; // can also get it from process.env.PORT
var router = express.Router();
//this is like interceptor for every route to validate all requests, logging for analytics
router.use(function (req, res, next) {
console.log('route intercepted');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.json({ message: "welcome to restful node proxy layer to business processes" });
});
router.route('/someroute').post(function(req, res) {
rest.postJson('http://localhost/api/sg', req.body).on('complete', function(data, response) {
console.log(response);
}
).on('error', function(data, response) {
console.log('error');
});
});
app.use('/api', router); //all routes are prefixed with /api
app.listen(port);
console.log("server is running magic happens from here");

Resources