Node Js express router not working - javascript

js and i am learning node js along with express and I was learning express routing I have following code in rest.js
const http = require('http');
const express = require('express');
const widgetRouter = require('./rest/widgets');
const app1 = express();
const server = http.createServer(app1);
app1.get('/api',widgetRouter);
server.listen(3000,function(){
console.log('server started in port 3000');
});
const app = express();
and I also have widgets.js file
const express = require('express');
const widgetRouter = express.Router();
widgetRouter.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
widgetRouter.route("/widgets/:widgetId")
.get()
.put()
.delete();
module.exports = widgetRouter;
but When I try to test the rest api(http://localhost:3000/api/widgets) from postman it says Cannot GET /api/widgets

You have imported and initialized the express module, but then you start a server with the http module. You should use only Express:
Also you should use app.use('/api',widgetRouter) instead of app.get('/api', widgetRouter) which is an express middleware.
const express = require('express');
const app = express();
const widgetRouter = require('./rest/widgets');
app.use('/api', widgetRouter);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000, function(){
console.log('server started in port 3000');
});

You can also try that.
rest.js
const express = require('express');
const http = require('http');
const router = express.Router();
const app = express();
require('./widgets')(app, router);
app.get('/', function(req, res) {
res.send('Home');
});
app.listen(3000,function(){
console.log('server started in port 3000');
});
widgets.js
module.exports = function(app, router){
router.route("/widgets")
.get(function(req,res){
res.json({"abc":"hello"});
})
.post();
router.route("/widgets/:widgetId")
.get()
.put()
.delete();
app.use('/api', router);
});

Related

Node.js Error: Cannot GET/ from running on the web browser

So here I have 2 route files and 1 controllers for each.
My first router that is root, is working fine !
but my second route that is /teacher is giving me this error "Cannot GET /teacher"
I literally copy pasted the root route code and changed the variable names still its not working.
following are my files:
server.js
const express = require('express');
const dotenv = require('dotenv');
const root_rt = require('./routes/root-rt');
const teacher_rt = require('./routes/teacherlogin-rt')
dotenv.config();
const uri = process.env.DB_URI;
const port = process.env.PORT;
const app = express();
app.use(express.json());
app.get('/', root_rt);
app.get('/teacher', teacher_rt);
app.listen(port, () =>{
console.log(`server started on http://localhost:${port}`);
});
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.route('/')
.get(teacherController.login);
module.exports = router;
teacher-cnt
module.exports.login = function (req, res) {
res.send('this is teacher login page');
};
Thank you in advance.
When using routers, you shouldn't use app.METHOD() to mount them, but app.use():
app.use('/', root_rt);
app.use('/teacher', teacher_rt);
Make the below change in your teacherlogin-rt.js, it will start working
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.get('/', teacherController.login);
module.exports = router;
server.js
app.use('/', root_rt);
app.use('/teacher', teacher_rt);

Why does my express router not respond to my get request?

So i have made a simple express app, but i have been trying for several hours to get a response to a simple get request when i visit http://localhost:3000/
This is my app.js
// IMPORTS
const express = require('express')
const mongoose = require('mongoose')
const customerRouter = require('./routes/customerRoute.js')
const app = express()
const PORT = 3000
// CONNECTION
mongoose.connect('mongodb://localhost/Customers', {useUnifiedTopology: true })
mongoose.connection.on('open', () => {console.log('Connected to database.')})
//APP USE ROUTES AND JSON
app.use(express.json)
app.use('/customers',customerRouter)
app.get('/', (req, res) => {
res.send('Home')
})
// APP PORT SET
app.listen(PORT)
console.log('Server started on port 3000')
This is my routes file
const express = require('express')
const router = express.Router()
console.log('into the router')
router.get('/', (req, res) => {
console.log('GET request')
})
module.exports = router
Substitute app.use(express.json) with app.use(express.json()) and everything will work. You have a mistake in this middleware that parses incoming requests with JSON payloads.
Source: express docs
You made a mistake in middleware app.use(express.json()) is a function not a property of the express object.

Node Express Server Cannot GET “/”

const https = require("http");
const app= require('./app');
const port = 8080;
const server = https.createServer(app);
server.listen(port)
I am not sure of what you were trying to do but you can use express in this way:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
/// do something here
})
app.listen(8080)
Also, check express guide : http://expressjs.com/en/starter/hello-world.html

Express js router not working

This is my home.js code
// import modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require ('cors');
var path = require ('path');
var app = express();
const route= require('./routes/route');
//port no
const port =3000
app.use(cors());
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
app.use('./api', route);
//testing server
app.get('/', (req,res)=>{
res.send('foober');
})
app.listen(port,()=>{
console.log('server started at port:' + port);
});
And this the route.js code
const express = require('express');
const router = express.Router();
router.get('/contacts', (req, res, next )=>{
res.send('retrieve contact');
});
module.exports =router;
But whenever I run 'localhost:3000/api/contacts' i get 'Cannot GET /api/contacts' error. I am very new at this, what am I doing wrong?
A dot in an url is there to seperate domains, if your route is mounted at ./api you would have to visit yourserver.com./api which won't work as the url is invalid.

How to create a Front end (VueJS) for an API created by using NodeJS + Express + MongoDB

I've created a REST API by using Express. All the info is stored in MongoDB and all the endpoints of an API return JSON.
index.js (main)
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
/* Connect to a DB */
mongoose.connect('mongodb://localhost/cars');
mongoose.Promise = global.Promise;
app.use(bodyParser.json());
/* Initialize routes */
app.use('/api', require('./routes/api'));
/* Listening on port 3000 */
app.listen(process.env.port || 3000, function() {
console.log('I\'m ready for requests...');
});
/routes/api.js
const express = require('express');
const router = express.Router();
const Car = require('../models/car');
router.get('/cars', function(req, res) {
res.send({
type: 'GET'
});
});
router.post('/cars', function(req, res) {
Car.create(req.body).then(function(car) {
res.send(car);
});
});
module.exports = router;
How can implement Vue.js into my API?

Categories