No response from nodejs api - node.js

This is my code i tried to send a request through http://localhost:3000/api/post/article using postman but i received cannot get as error.
It's working without using router.get but instead using app.get, so i think the problem is with the router.
This is the server.js file
const http = require("http");
const app = require("./app");
app.set("port", process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(process.env.PORT || 3000);
this is the app file
const express = require("express");
const postRoutes = require("./routes/post");
const app = express();
app.use("api/post", postRoutes);
module.exports = app;
This is the router file
const express = require("express");
const router = express.Router();
const postCtrl = require("../controllers/post");
router.get("/article", postCtrl.specArticle);
module.exports = router;
This is the controller file
module.exports.specArticle = (req, res) => {
res.status(200).json({ message: "working currently" });
};

Change this:
app.use("api/post", postRoutes);
to this:
app.use("/api/post", postRoutes);
As best I know, all paths in your route handlers should start with / (at least I have no idea why you would ever not start them with a /).

Related

Nodejs is not able to work after creating different routing files

I have an error while running my index.js file after separating the code into different files.
I'm running index.js in the terminal in the right folder as required.
This is my index.js file:
const express = require("express");
const app = express();
const Joi = require("joi");
const genres = require("./routes/genres");
const home = require("./routes/home");
app.use(express.json());
app.use("/api/genres", genres);
app.use("/api/home", home);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`you are listening to port ${port}`));
This is my genres file for routing:
const express = require('express');
const router = express.Router();
.
.
.My routing settings
.
.
module.exports = router;
This is the error that I get in vs code after running index.js via terminal:
Will be glad to get any assistance.
index.js
const genres = require("./routes/genres")(app);
const home = require("./routes/home")(app);
app.use("/api/genres", genres);
app.use("/api/home", home);
genre.js
const express = require('express');
const router = express.Router();
router
.get('/', async (req, res) => {
res.send('get data');
})
.post('/add', async (req, res) => {
res.send('get data');
})
module.exports = router;

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

Cannot GET /api

I have a problem with my post data to the server. Not sure why i get an error for get when i changed my rout to post.
routes/feedback.js
const express = require("express");
const router = express.Router();
const { emailFeedback } = require("../controllers/feedback");
router.post("/feedback", emailFeedback);
module.exports = router;
server.js
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
// import routes
const feedbackRoutes = require("./routes/feedback");
// app
const app = express();
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cors());
// routes
app.use("/api", feedbackRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
I believe the usual syntax for an express post route is as follows:
router.post("/feedback", function(req, res){
//grabbing the request body
console.log(req.body);
console.log(req.bodt);
//posting the request
res.json(req.body);
});
A callback function needs to be passed in and receive those request and response parameters (req, res).

Dynamic BaseUrl in ExpressJs

I'm trying to set the base URL for an Express app on startup.
I can hardcode the base URL and it works just fine:
app.use("/mybaseurl", routes);
However, if I try to use a variable instead which I can export on startup, it fails:
const baseUrl = "/mybaseurl";
app.use(baseUrl, routes);
The above doesn't work.
What am I missing?
test this code, work for me: http://localhost:3000/test
app.js:
const express = require('express');
const userRouter = require('./user');
const app = express();
app.use(express.json());
const baseUrl = '/test';
app.use(baseUrl, userRouter);
app.listen(3000, ()=> {
console.log('Server is up on port ', 3000)
});
user.js:
const express = require('express');
const router = new express.Router();
router.get('/', async (req, res) => {
res.status(200).send('hello');
});
module.exports = router;

Having two seperate routes in node/express, where one accepts all the requests

In my node/express app, I have the following app.js file with the following routing
const express = require('express');
const path = require('path');
const logger = require('./middleware/logger');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/wsserver', require('./routes/wsroutes'));
app.use('/', require('./routes/company'));
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
console.log('server runs on port ', port);
});
Every request that goes to http://localhost:8080/wsserver, is handeld by wsroutes. I am planning to setup a websockets server in there, but for now contains
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('ws');
})
module.exports = router;
The / handles all the other requests and its handled by the company that contains
router.get('/',(req, res)=>{ ....
router.get('/:companyName/:id?/:employ?',(req, res)=>{ ...
etc
As you can guess, the problem is that when I go to http://localhost:8080/wsserver, is handled by the / route and the company route. I get the interface and the message no company named wsserver , because the wsserver becomes an argument in the router.get('/:companyName/:id?/:employ?' route.
How can I still have both routes, not change the / one and have them both work correctly? I tried to change positions in the routes like so
app.use('/', require('./routes/company'));
app.use('/wsserver', require('./routes/wsroutes'));
ans still nothing.
What else can I do ?
Thanks

Resources