Trouble making a POST request - Express - node.js

i'm new to the forum and i've been doing a project for my university and i got a problem with my post request. Can anyone help me with this?
I'm using express and mongo.
Here's my code:
server.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var methodOverride = require('method-override');
var app = express();
app.use(cors());
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
mongoose.connect('mongodb://localhost/futbol', { useMongoClient: true });
require('./Modelos/partidos.js');
app.use(require('./Rutas'));
var router=express.Router();
app.use(router);
app.listen(port, () => {
console.log('We are live on ' + port);
});
index.js
var router=require('express').Router();
router.use('/api/partidos', require('./partidos'));
module.exports=router;
partidos.js
var mongoose = require('mongoose');
var router = require('express').Router();
var bodyParser = require('body-parser');
var Partido = mongoose.model('partido');
// GET ALL
router.get('/', (req, res, next) => {
Partido.find({})
.then(partidos => {
if(!partidos){ return res.sendStatus(401); }
return res.json({'partidos': partidos})
})
.catch(next);
});
// GET BY ID
router.get('/:_id', (req, res, next) => {
let _id = req.params._id
Partido.findById(_id)
.then(partidos => {
if(!partidos){ return res.sendStatus(401); }
return res.json({'partidos': partidos})
})
.catch(next);
});
// POST PARTIDO
router.post('/', (req, res, next) => {
var _id = req.body._id;
var id_equipo1 = req.body.id_equipo1;
var nombre_equipo1 = req.body.nombre_equipo1;
var id_equipo2 = req.body.id_equipo2;
var nombre_equipo2 = req.body.nombre_equipo2;
var fecha_inicio = req.body.fecha_inicio;
var hora_inicio = req.body.hora_inicio;
res.send("post _id: "+_id+" - id_equipo1: "+id_equipo1+" - nombre_equipo1 "+nombre_equipo1+" - id_equipo2 "+id_equipo2+" - nombre_equipo2 "+nombre_equipo2+" - fecha_inicio "+fecha_inicio+" - hora_inicio "+hora_inicio);
});
module.exports=router;
The POST method that is throwing an error is in partido.js
I'm also using RestEasy to make my post request with this parameters:
Url: http://localhost:3000/api/partidos
Method: POST
Headers: Content-Type: application
Body:
{
"_id" : "2",
"id_equipo1" : "4",
"nombre_equipo1" : "Independiente",
"id_equipo2" : "5",
"nombre_equipo2" : "River",
"fecha_inicio" : "10/10/17",
"hora_inicio" : "21:00:00"
}
This is the result:
{
post _id: undefined,
id_equipo1: undefined,
nombre_equipo1: undefined,
id_equipo2: undefined,
nombre_equipo2: undefined,
fecha_inicio: undefined,
hora_inicio: undefined
}
Thanks in advance!

Related

why my console.log(req.body) give: {} in nodejs

I want to update a post in my bdd with the new value. When i click for validate i have an empty req.body!
exports.updatePost = (req, res, next) => {
Post.update(
{
message: req.body.message,
},
{ where: { id: req.params.id } }
)
.then(() => res.status(200).json({ message: "post modifié" }))
.catch((error) => res.status(500).json({ error }));
console.log(req.body)
console.log(req.params.id)
};
As you can see i console log my req.body for check, my req.paramas.id give me the right thing. Since i have this problem i decided to check my post route and my app.js but i didn't see anything.
my route is like this:
const express = require("express");
const router = express.Router();
const postCtrl = require("../controllers/post");
const auth = require("../middleware/auth");
const multer = require("../middleware/multer-configs");
//DIFFERENTE ROUTES POUR LES POSTS, COMPRENNANTS LES DIFFERENTS MIDDLEWARE UTILES ET D'AUTHENTIFICATION
router.get("/", auth, postCtrl.getAllPost);
router.post("/", auth, multer, postCtrl.createPost);
router.delete("/:id", auth, postCtrl.deletePost);
router.put("/:id", auth, postCtrl.updatePost);
router.get("/:id", auth, postCtrl.getPostByUserId);
module.exports = router;
and my app.js is like this:
const express = require("express");
require("dotenv").config();
const helmet = require("helmet");
const cors = require("cors");
const db = require("./models");
const path = require("path");
const bodyParser = require("body-parser");
const userRoutes = require("./routes/user");
const postRoutes = require("./routes/post");
const likeRoutes = require("./routes/like");
const commentRoutes = require("./routes/comment");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//MODULE C.O.R.S
app.use(cors());
app.use(express.urlencoded({ extended: true }));
// POST
app.use("/api/post", postRoutes);
I don't really understand why my backend can't see the back or don't give me the result of my body.
my client side is like this actually:
const updatePost = () => {
if (textEdit) {
const data = new FormData();
data.append("message", textEdit);
axios.put(`http://localhost:5000/api/post/${id}`, data, {
headers: {
Authorization: `Bearer ${sessionStorage.getItem("authToken")}`,
},
})
.then((res) => {
console.log(res);
console.log(id)
console.log(message)
console.log(textEdit)
})
}
}

express nodejs body is empty after post request

I have tried all out there but still the post request is giving me an empty. I checked in browser and also in postman the values are sent via the payload, but when getting via the router post, req.body is empty
main
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
// var bodyParser = require("body-parser"); body parser also didnt work
const app = express();
// app.use(
// bodyParser.urlencoded({
// extended: true,
// })
// );
// app.use(bodyParser.json());
app.use(cors());
app.use(express.urlencoded({ extended: true })); // interchanged this below express.json didnt work
app.use(express.json());
const PORT = 3009;
// import routes
const router = require("./routes/route");
app.use("/api", router);
// connect mongo start
const uri =
"mongodb+srv://adminuser:password#cluster0.gtkdj.mongodb.net/mydb?retryWrites=true&w=majority";
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(uri, options);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
console.log("Mongo Connected");
});
app.listen(PORT, () => {
console.log("Port is connected at ", PORT);
});
model
const mongoose = require("mongoose");
const dataSchema = mongoose.Schema({
name: {
type: String,
},
});
const dataModel = mongoose.model("data", dataSchema);
module.exports = dataModel;
routes
const express = require("express");
const router = express.Router();
const dataModel = require("../model/schema");
router.post("/new_items", (req, res) => {
const data = new dataModel({
name: req.body.name,
});
console.log(data, req.body);
data
.save()
.then((item) => res.send(item))
.catch((err) => res.status(400).send(err));
});
console output { _id: 6022f0c0b3dd8f2sdc5302f9 } {}
The req body is empty. Please help me on this. Thanks
The codes were correct. But, the post request header was not present. After passing the header, it worked as intended.
await fetch("http://localhost:3009/api/new_items/", {
method: "POST",
headers: {
"Content-Type": "application/json", // this was missing
},
body: JSON.stringify(body),
})

API posts x-www-form-urlencoded data but fails on json

I have a basic Mongo API.
During testing, I can easily post data with postman when it is x-www-form-urlencoded but when I use raw JSON, it is just blank.
I stored the body to see what was the difference and noticed that while using the x-www-form-urlencoded format there was data but when using JSON, my object was blank and doesn't post anything.
The data schema is as follows:
var mongoose = require('mongoose');
// Setup schema
var testSchema = mongoose.Schema({
fieldone: {
type: String,
required: true
},
fieldtwo: {
type: String,
required: true
},
fieldthree: {
type: String,
required: true
},
fieldfour: String,
fieldfive: String,
fieldsix: String
});
// Export model
var test= module.exports = mongoose.model('test', testSchema);
module.exports.get = function(callback, limit) {
test.find(callback).limit(limit);
}
The controller is as below:
// Controller.js
// Import model
Test= require('./Model');
// insert new test
// Handle create actions
exports.new = function(req, res) {
const {
fieldone,
fieldtwo,
fieldthree,
fieldfour,
fieldfive,
fieldsix
} = req.body
var test= new Test(req.body);
// console log for testing if the data shows
console.log(test)
// save and check for errors
test.save(function(err) {
// if (err)
// res.json(err);
res.json({
message: 'New test created!',
data: test
});
});
};
Below is my api-routes
// api-routes.js
// Initialize express router
const router = require('express').Router();
// Set default API response
router.get('/', function(req, res) {
res.json({
status: 'alls good',
message: 'alls good',
});
});
// Import controller
const testController = require('./Controller');
// routes
router.route('/test')
.get(testController.index)
.post(testController.new);
// Export API routes
module.exports = router;
Below is my index.js:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const app = express();
// Import routes
var apiRoutes = require("./api-routes");
var corsOptions = {
origin: '*',
credentials: true
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoutes);
// mongo con
mongoose.connect('mongodb://localhost/mongodojo', { useNewUrlParser: true
});
var db = mongoose.connection;
// error check
if (!db)
console.log("Error while connecting")
else
console.log("connection successful")
// Setup server port
const port = process.env.PORT || 3000;
app.get('/', (req, res) => res.send('Welcome'));
Is there anything in my code that could be causing this?

Can Not POST NodeJS Express

I was trying to make an axios post request to an express server and I receive that Error: Request failed with status code 404 at createError. Postman says Can Not POST. I don't know what could be wrong, i'm new in all this, so all the help it's good, thanks.
Axios and Express server are from 2 different link. They are google cloud function.
Thanks for the help
Axios Post Request :
exports.notification = (req, res) => {
var axios = require('axios');
var https = require('https');
var bodyParser = require('body-parser');
var config = {
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Type' : 'text/html',
'Content-Type' : 'application/json' }
};
var info = {
ids:[req.body.id,req.body.id1],
type: req.body.type,
event: req.body.action,
subscription_id: req.body.subid,
secret_field_1:null,
secret_field_2:null,
updated_attributes:{
field_name:[req.body.oname,req.body.nname]}
};
var myJSON = JSON.stringify(info);
return axios.post('https://us-central1-copper-mock.cloudfunctions.net/api/notification-example', myJSON)
.then((result) => {
console.log("DONE",result);
})
.catch((err) => {
console.log("ERROR",err);
console.log("Error response:");
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
})
};
Express Server
const express = require ('express');
const https = require ('https');
const bodyParser = require ('body-parser');
const app = express();
const port = 8080;
// ROUTES
var router = express.Router(); // get an instance of router
router.use(function(req, res, next) { // route middleware that will happen on every request
console.log(req.method, req.url); // log each request to the console
next(); // continue doing what we were doing and go to the route
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/',require ('./Routers/API/home'));
app.use('/leads',require ('./Routers/API/leads'));
app.use('/people',require ('./Routers/API/people'));
app.use('/companies',require ('./Routers/API/companies'));
app.use('/opportunities',require ('./Routers/API/opportunities'));
app.use('/projects',require ('./Routers/API/projects'));
app.use('/tasks',require ('./Routers/API/tasks'));
app.use('/activities',require ('./Routers/API/activities'));
app.use('/notification-example',require ('./Routers/API/notification_example'));
app.use('/', router); // apply the routes to our application
// START THE SERVER
// ==============================================
app.listen(port);
console.log('Listening ' + port);
module.exports={
app
};
Notification Route
const express = require('express');
const router = express.Router();
//const notification_example = require('../../Notification');
router.get('/', function(req, res) {
console.log('DATA',JSON.parse(res.data));
console.log('BODY',JSON.parse(res.body));
});
module.exports = router;

Error: Route.post() requires a callback function but got a [object Undefined]

I have created a service in node.js for basic crud operations. However when I start service it throws Route.get() requires a callback function but got a [object Undefined] error. I am not able to figure out where the error is.
Here is my code.
Models:
agreement_master.js.
const mongoose = require('mongoose');
const agreementmaster = mongoose.Schema({
ClientId:{type:Number},
UserId:{type:Number},
StartDate:{type:Date},
});
var Agreement = module.exports =
mongoose.model('Agreement',agreementmaster);
module.exports.addmAgreement=function (data,callback){
data.save(callback);
}
module.exports.getallmAgreement= function (data,callback){
var query = {status:true};
Agreement.find(query, callback);
}
routes:
agreement_master.js
var express = require('express'),
router = express.Router(),
magreement = require('../controller/agreement_master');
router.post('/addmAgreement', magreement.addmAgreement);
module.exports = router;
Controller:
agreement_master.js
const Agreement= require('../models/agreement_master');
exports.addmAgreement = function (req, res){
var data = JSON.parse(JSON.stringify(req.body));
var agreement = new Agreement(data);
agreement.ClientId = req.body.ClientId;
agreement.UserId= req.body.UserId;
agreement.StartDate=new Date();
Agreement.addmAgreement(agreement, function (err, obj) {
if (err) return res.json({err, status:'error'});
if(obj){
return res.json({
message:'agreement added',
});
}
});
};
index.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');
const cookieParser = require('cookie-parser');
mongoose.connect('mongodb://local/local-host')
const app = express();
error comes at this part in the below line:
const agreement = require('./routes/agreement_master');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(expressValidator());
app.use(cookieParser());
//Add Routes here
app.use('/agreement', agreement);
app.set('port', (process.env.PORT || 3001));
var server = app.listen(app.get('port'), function(){
console.log('Server Started on port ' + app.get('port'));
});
module.exports = app;
user module.exports instead of exports.
exports doest export anything and will not be used by require();
module.exports.addmAgreement = function (req, res){
var data = JSON.parse(JSON.stringify(req.body));
var agreement = new Agreement(data);
agreement.ClientId = req.body.ClientId;
agreement.UserId= req.body.UserId;
agreement.StartDate=new Date();
Agreement.addmAgreement(agreement, function (err, obj) {
if (err) return res.json({err, status:'error'});
if(obj){
return res.json({
message:'agreement added',
});
}
});
};
try this
router.post('/addmAgreement', function(req, res){
magreement.addmAgreement
});
instead of
router.post('/addmAgreement', magreement.addmAgreement);

Resources