NodeJs route not working - node.js

I am new to NodeJs. I am getting error with below code.
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
port = process.env.PORT || 9090,
mongoose = require('mongoose'),
Cheque = require('./models/cheque'),
router = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mongoose.connect('http://localhost:27017/utils/chequeman');
router.route('/cheques').post(function (req, res) {
console.log('u r in cheques.');
var cheque = new Cheque();
cheque.chequeReceiptDate = req.body.chequeReceiptDate;
cheque.save(function (err) {
if (err)
res.send(err)
res.json({ message: 'Cheque details added' });
});
});
app.use('/api', router);
app.listen(port);
console.log('Magin happens at' + port);
When I am trying POST request in postman I am getting response as "Cannot POST /api/cheques"
Please help.

Try to declare the variables that you are using.
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let port = process.env.PORT || 9090;
let mongoose = require('mongoose');
let Cheque = require('./models/cheque');
let router = express.Router();
Take your API static
app.use('/CHEQUEDIRECTORY', express.static(__dirname + '/CHEQUEDIRECTORY'))
Don't forget to export modules on you API.
Have you installed the packages correctly?

Related

Browser showing "Cannot GET /api/posts/ " instead of "hello" from res.send('hello')

My index.js file:
//Dependencies
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const posts = require('./routes/api/posts.js');
//Configuration
const port = process.env.PORT || 5000;
//App object
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
//Main app
app.use('api/posts',posts);
//Starting server
app.listen(port,()=>{
console.log(`server running at ${port}`);
});
My Api file:
//Dependencies
const express = require('express');
const mongodb = require('mongodb');
//Mini app
const router = express.Router();
//Get post
router.get('/',(req,res)=>{
res.send('hello');
});
//Add post
//Delete post
module.exports = router;
I'm expecting to get "hello" in my browser but constantly getting "Cannot GET /api/posts/" in firefox and postman. What should I do now?
Correction :-
//Main app
app.use('/api/posts',posts);

Both POST/GET requests yield a 404 error in Postman. Is my Express routing to blame?

I am intending to set up a Node.js server with MongoDB to handle HTTP CRUD requests. Upon setting up my endpoint I was initially able to receive POST/GET requests, however the handling of the document objects became the issue. Upon trying to fix this issue I am now unable to POST/GET at all? Is this simply a syntax issue or is my code doomed?
const MongoClient = require('mongodb').MongoClient;
var QRCode = require('qrcode');
var canvasu = require('canvas');
var express = require('express');
var mongoose = require('mongoose')
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var db;
var collection
var Patient = require('./ShiftAssist/models/patientModel');
var router = express.Router();
''
CODE FOR CONNECTION
''
router.get('/patients/:Pnum', function(req,res,next){
Patient.findOne({Pnum:req.params.Pnum},function(err,patient){
if (err) return next(err);
res.json(patient);
})
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port ' + port + '!');
});
Expected: GET request to http://127.0.0.1:3000/patients/XXXXXX with a document identifier, returns entire document
Actual: Timeout Error
try to change you route by /patients/:Pnum
and your request should be http://127.0.0.1:3000/patients/XXXXXX
source: https://expressjs.com/en/guide/routing.html
EDIT: Code i used so far
var express = require('express');
var app = express();
var router = express.Router();
router.get('/patients/:Pnum', function (req, res, next) {
setTimeout(() => res.json({ ok: req.params.Pnum }), 1000)
});
app.use('/', router);
app.listen(3000);

NODE Cannot GET routes function

I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.

Express perform a function before responding

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
var test;
function SomeFunction(){
....some function that calculates a value
res.json({ message: 'Your value is' + test });
}
});
app.use('/api', router);
app.listen(port);
I want to perform some function to calculate a value before returning it. As is stands the server will respond immediately. I am sure this is very basic but i looked everywhere and cant find an answer about how to wait for my express server to calculate the value before issuing a response.
You are not calling your function SomeFunction anywhere. If you call it, express will wait. Just write after the function definition: SomeFunction();.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
var test;
function SomeFunction(res){
....some function that calculates a value
res.json({ message: 'Your value is' + test });
}
//call it with res parameter
someFunction(res);
});
app.use('/api', router);
app.listen(port);

Error in implementing router

Here is my code.
server.js
var express = require('express'),
bodyParser = require('body-parser'),
log = require('./libs/log')(module),
api = require('./libs/api.js'),
app = express();
// settings
app.set('port', 5000);
// to process post requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// routes
rawQuestionRouter = require('./routes/rawQuestionRoutes.js');
app.use('/rawQuestions', rawQuestionRouter);
and routes/rawQuestionRoute.js:
var express = require('express');
var routes = function() {
var rawQuestionRouter = express.Router();
rawQuestionRouter.route('/test')
.post(function(request, response) {
log.debug(request.body);
response.send('raw question saved');
});
return rawQuestionRouter;
}
module.exports = routes;
Update:
When I make a POST request on '/rawQuestions/test' the server don't respond. Why?
You're exporting the routes function, which is not a router (it returns one, but that's not the same).
There are several solutions:
// server.js
app.use('/rawQuestions', rawQuestionRouter());
Or:
// routes/rawQuestionRoute.js
module.exports = routes();
Or just remove the entire routes function altogether and export the router instance directly.

Resources