I am trying to create a REST API using Express JS.
console.log(req.body) gives undefined as output,
this is my code in routes.js page
const express = require('express');
const router = express.Router();
router.post('/post',async (req,res) => {
console.log("inside post router");
console.log(req.body);
const data = new Model({
name: req.body.name,
age: req.body.age
})
try {
const dataToSave = await data.save();
res.status(200).json(dataToSave)
}
catch(error) {
res.status(400).json({message:error.message})
}
})
This is the code in index.js file
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();
app.use('/api',routes);
User middlewares ,for parsing the post body in your index.js file
const express = require('express');
const mongoose = require('mongoose');
const routes = require('./Routes/routes');
const app = express();
app.use(express.json()) ; //parsing application/json
app.use(express.urlencoded({extended: false}) ;
app.use('/api',routes);
Make sure to use them ,before you configure your routes
See reference
Related
I'm trying to make a simple GET request to my localhost:8080.
When I make the GET request with Postman, I set a simple cookie. Now, in the main file, I've:
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());
const app_router = require('./routes/router');
app.use("/api", app_router);
app.use(express.static('public'));
app.listen(8080, function () {
console.log('Outdoor Localization GNSS middleware.');
});
In routes/router.js I have:
var express = require('express')
const router = express.Router();
const axios = require('axios');
const url = 'http://10.10.0.145:80/api'
router.use(express.json());
router.get('/*', function (request, response) {
console.log(request.Cookie)
axios
.get(request_url)
.then(res => {
console.log(request.Cookie)
})
.catch(error => {
console.error(error)
})
});
The problem is that request.Cookie always return undefined...why is this happening?
you should be accessing the property request.cookies instead of request.Cookie
I am trying to insert a category in the database following the instructions of a course I am taking and I am unable to insert it with the create method. It shows ... loading in Postman and nothing happens and no error message appears on the console. Here are my files.
app.js
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const expressValidator = require('express-validator')
require('dotenv').config()
//import routes
const authRoutes = require('./routes/auth')
const userRoutes = require('./routes/user')
const categoryRoutes = require('./routes/category')
// app
const app = express()
// db
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log('DB Connected'))
// middlewares
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser())
app.use(expressValidator())
// routes middleware
app.use('/api', authRoutes)
app.use('/api', userRoutes)
app.use('/api', categoryRoutes)
const port = process.env.PORT || 8000
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
routes/category.js
const express = require('express')
const router = express.Router()
const { create } = require('../controllers/category')
const { requireSignin} = require('../controllers/category')
const { userById } = require('../controllers/user')
router.post('/category/create/:userId', function(req, res){
requireSignin,
create
});
router.param("userId", userById)
module.exports = router
controllers/category.js
const Category = require("../models/category")
const { errorHandler } = require("../helpers/dbErrorHandler")
exports.create = (req, res) => {
const category = new Category(req.body)
category.save((err, data) => {
if(err) {
return res.status(400).json({
error: errorHandler(err)
})
}
res.json({ data })
})
}
models/category.js
const mongoose = require('mongoose')
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxlength: 32
}
},
{ timestamps: true }
);
module.exports = mongoose.model('Category', categorySchema)
In order to make sure that data is actually being returned, your create function needs to be asynchronous. Adding async/await to the save function should confirm that you are properly saving the data to the database before returning.
It appears you have an error in your route setup. I assume requireSignin and create should be middleware functions.
So instead of
router.post('/category/create/:userId', function(req, res){
requireSignin,
create
});
you should try this
router.post('/category/create/:userId', requireSignin, create);
// assuming 'create' is the last one, since you are ending the request there
// also assuming that 'requireSignin' is setup as middleware, calling next function
I´m trying to create an API Rest in NodeJs with Express.
I have my index.js with the following code:
const express = require('express');
const routesV1 = require('./routes/v1/index');
const app = express();
routesV1(app);
app.listen(4000, () => {
console.log('Running on port: 4000');
});
then i have a routes folder with another "index.js" and a "usersRoutes".
Here´s the code of the userRoutes:
const express = require('express');
const userController = require('../../controllers/v1/UserController');
const router = express.Router();
router.post('/create', userController.createUser);
router.post('/update', userController.updateUser);
router.post('/delete', userController.deleteUser);
router.get('/get-all', userController.getUsers);
module.exports = router;
and the code of the index.js into the routes folder:
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('api/v1/users', userRoutes);
};
but when i´m consuming via Postman, with the following url: http://localhost:4000/api/v1/users/create I´m receiving a 404 error code.
Can anybody help me? thanks
I resolved it adding '/' to the route in routes/index.js
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/products', productRoutes);
};
I'm getting "Cannot GET /speakers" error on my browser when I am trying to access http://localhost:3000/speakers from the following code:
My Server.js File
const express = require('express')
const path = require('path')
const routes = require('./routes')
const app = express()
const port = 3000
app.set('view engine','ejs')
app.set('views', path.join(__dirname,'./views'))
app.use(express.static(path.join(__dirname,'./static')))
app.use('/', routes())
app.listen(port,()=>{
console.log(`Express server listening on port ${port}!`)
})
My Script.js File
This is my server.js file where I've declared various variables
const express = require('express')
const router = express.Router()
module.exports = () =>{
router.get('/',(request, response) =>{
return response.send('Speakers List')
})
router.get('/:shortname',(request, response) =>{
return response.send(`Detail page of {request.params.shortname}`)
})
return router;
}
My index.js file
const express = require('express')
const speakersRoute = require('./speakers')
const feedbackRoute = require('./feedback')
const router = express.Router()
module.exports = () =>{
router.get('/',(request, response) =>{
response.render('pages/index',{ pageTitle: 'Welcome'})
})
router.use('./speakers', speakersRoute())
router.use('./feedback', feedbackRoute())
return router
}
Can anyone help me on this?
Have you try change './speaker' to '/speaker' ?
// router.use('./speakers', speakersRoute())
router.use('/speakers', speakersRoute())
Getting the error
Route.post() requires a callback function but got a [object Undefined]
I have checked a few of these errors here in SO and they do not pertain to what I have, at least not what I have seen.
I have this same style of syntax in another application and it's working just fine so I am not sure where this is going wrong. I have things importing and exporting correctly, or at least so I think.
index.js
const express = require("express");
const bodyParser = require('body-parser');
const partial = require("express-partial");
const cors = require('cors');
const mysql = require('mysql');
const app = express() ;
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(partial());
// ************************ROUTES*******************************
const longSplits = require('./routes/longs.js')
app.use(longSplits);
longs.js
const express = require("express");
const router = express.Router();
const {
newLongTrade
} = require('../splits/editLong.js')
//This is my first split route
router.post('/', newLongTrade);
module.exports = router;
Here is the "controller" part of the code.
const newLongTrade = (req,res) => {
console.log(req.body.data);
res.send("Got it in the splits!");
}
module.exports = {
newLongTrade
};