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
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;````
I am using express.js framework for my node.js server.
This is how I setup my server.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var createUsers = require('./routes/users/createUsers');
var updateUsers = require('./routes/users/updateUsers');
var deleteUsers = require('./routes/users/deleteUsers');
var readUsers = require('./routes/users/readUsers');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'project'
});
res.locals.connection.connect();
next();
});
// 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('/', index);
app.use('/createUsers', createUsers);
app.use('/updateUsers', updateUsers);
app.use('/deleteUsers', deleteUsers);
app.use('/readUsers', readUsers);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.ejs');
});
var http = require('http');
module.exports = app;
var server = http.createServer(app);
server.listen(4000);
This is my readUsers.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
//console.log("pending data");
res.locals.connection.query('SELECT id,name,email,username,address,phone,status FROM user', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
});
});
module.exports = router;
My server is listen at port 4000. My react frontend componentDidMount() function use axios.get("http://localhost:4000/readUsers") to read the data from database and it worked well.
However, if I directly type in http://localhost:4000/readUsers in my browser, it will directly connect to my database and read all User data and displayed the data in browser. This is not I want because everyone can read my data if they know this address. Any way to prevent this issue?
Add middleware to your router. here's the doc Router-level middleware
Express have many middleware, one of it is route-level middleware. This middleware handle anything between users and your function.
Here is the example i fetch from the documentation.
var app = express()
var router = express.Router()
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
In your case you may add some permission validation before request. Usually it's an API key, but it can be anything, secret word in header, secret parameter, everything.
Here is the example for your case.
function isPermitted(req, res, next) {
var permitted = false;
// Your validation here, is your user permitted with this access or not.
if (permitted) {
next();
} else {
res.send('Sorry, you are not belong here.');
}
}
/* GET home page. */
router.get('/', isPermitted, function(req, res, next) {
//console.log("pending data");
res.locals.connection.query('SELECT id,name,email,username,address,phone,status FROM user', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
});
});
Use POST instead of GET as method for request.
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");
This is very strange in that Express JS is sending the console.log output to the client without res.send being used.
Calling the /api POST endpoint shows the "Hello" from the parseJSON back to the client.
How can I get this to stop?
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
extended: false
}));
app.get('*', function(req, res, next) {
var err = new Error();
err.status = 404;
next(err);
});
// handling 404 errors
app.use(function(err, req, res, next) {
if (err.status !== 404) {
return next();
}
res.send(err.message || '** 404 error **');
});
app.post('/api', function(req, res) {
parseJSON(req.body);
res.status(200).end();
});
app.listen(80);
function parseJSON(jsonData)
{
console.log("HELLO");
}