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).
Related
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);
In a nodejs project I'm getting this error : 'app.use() requires a middleware function error at the line 7 of this file :
const Router = require('./route');
const express = require('express');
const app = express();
const port = 3001;
app.use(express.json());
app.use(Router);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
and I really don't get why I'm getting this error.
here are the routes files
const ProduitRouter = require('./produit');
const router = require("express").Router();
router.use("/produit", ProduitRouter);
module.exports = router;
const ProduitControleur = require("../controleur/produitDB");
const Router = require("express-promise-router");
const router = new Router;
//const router = require("express").Router();
router.get('/:id', ProduitControleur.getProduit);
router.post('/', ProduitControleur.postProduit);
router.patch('/', ProduitControleur.updateProduit);
router.delete('/', ProduitControleur.deleteProduit);
module.exports = router;
Try this.
In app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const http = require('http');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
require('./routes')(app); // path of file in which all your routes are defined.
module.exports = app;
in router file where all routes are define.
const express = require('express');
const router = express.Router();
const controller = require('path of controller');
router.post('/upload/file', verifyToken, controller .functionName);
module.exports = router;
As I can see, there is no imports for Router file
The api is being consumed from a react app with axios
OPTIONAL requests only come when I'm actually consuming POST requests
App.js
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
require('dotenv').config()
const app = express();
const authToken = require("./middlewares/auth_token");
const config = require('./config/config')
//SETTINGS
app.set('port', config.API_PORT || 4000);
//MIDDLEWARES
app.use(morgan('dev'));
app.use(cors());
app.use(express.json());
app.use(authToken);
app.use('/api/user', require('./routes/user'));
app.use('/api/user/auth', require('./routes/auth'));
app.use('/api/user/profile', require('./routes/profile'));
app.use('/api/user/events', require('./routes/events'));
module.exports = app;
index.js
const app = require('./app');
require('./database/database');
async function main() {
await app.listen(app.get('port'));
console.log(`Server on port ${app.get('port')}`);
}
main();
sorry for my english, greetings from Colombia
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 /).
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