Node and Express Routing - 404 error - node.js

I'm getting back 404 error using nodemon and not quite sure where the problem is. Any tips / resources appreciated!
project root
$ curl http://127.0.0.1:3000/v1/protected
Cannot GET /v1/protected
nodemon: "GET /v1/protected/ HTTP/1.1" 404 26 "-" "curl/7.49.1"
index.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
var router = require('./services/router');
mongoose.connect('mongodb://localhost:introToBackend/introToBackend');
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(express('/v1', router));
const PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';
console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);
services/router.js
var router = require('express').Router();
function protectedRoute(req, res, next) {
res.send("The secret!");
}
router.route('/protected')
.get(protectedRoute);
module.exports = router;

Try writing
express.use('/v1',yourRouter);
You do not need the express inside app.use

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

node_modules/express/lib/router/index.js:458 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

I am trying to create nodejs express application, I am facing weird issue while using routes
This is how my server.js looks
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/api',api);
app.use(express.static(path.join(__dirname,'dist')));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname,'dist/index.html'));
});
const port = process.env.port || 3000;
app.set('port',port);
const server = http.createServer(app);
server.listen(port,function(){
console.log('server running at port '+port);
});
I am getting following error "node_modules/express/lib/router/index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
"
Please let me know where I am going wrong
I just forgot to add module.exports = router in my api.js adding this solved my problem

Vhost + express why doesn't work?

I try to configure my node.js + express application for creation multiple domain server. This is my code, but unfortunately it's not working. Please explain me, what is wrong in this code?
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const vhost = require('vhost')
const app = express();
app.use(bodyParser.json());
// Port
const port = 8081;
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(vhost('*.localhost:8081', function(req, res, next){
res.send('Ok, its work.');
}));
app.listen(port, function(){
console.log('App is running on port '+ port);
});

How to check mongo database is connected?

I have mongodb up and running for the application how can i make sure when application start it is connected with db ?
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
config > db.js
module.exports = {
url : 'mongodb://localhost/test-dev'
}

Error: Cannot GET /

I am working in c9.io ide environment, I have written below code in server.js file
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var express = require('express');
var app = express();
var router = express();
var server = http.createServer(router);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/client'));
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/about', function (req, res) {
res.send('about');
});
After running node server.js in terminal the message given as
Your code is running at https://nodejs2-mujaffar.c9.io.
Important: use process.env.PORT as the port and process.env.IP as the host in your scripts!
Server listening at 0.0.0.0:8080
But after accessing https://nodejs2-mujaffar.c9.io/ url -- It is not rendering view only displaying message Error: Cannot GET /
What I am doing wrong?
Please help.
You seem to have created two instances of express which may be your problem.
Try changing:
var express = require('express');
var app = express();
var router = express();
var server = http.createServer(router);
to:
var express = require('express');
var app = express();
var server = http.createServer(app);
At the minute, your express app variable is not bound to your http server. You have instead bounded an unused instance called router. But then you have registered your routes to the app variable.

Resources