I am using Postman to learn about APIs. The contents of my server.js file is in the code below. However, when I send a post through Postman, the error "Cannot read property 'title' of undefined" keeps showing.
var Product = require("./model/product");
var WishList = require("./model/wishlist");
app.post("/product", function (request, response) {
var product = new Product();
product.title = request.body.title;
product.price = request.body.price;
product.save(function (err, savedProduct) {
if (err) {
response.status(500).send({ error: "Could not save product" });
} else {
response.status(200).send(savedProduct);
}
});
});
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3000, function () {
console.log("Swag Shop API runing on port 3000...");
});
The product.js file contains the code below.
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var product = new Schema({
title: String,
price: Number,
likes: { type: Number, default: 0 },
});
module.exports = mongoose.model("Product", product);
I tried to send the following json file through Postman but then the errorType: "Cannot read property 'title' of undefined " was showing.
{
"title": "Test Title",
"price": 100.00
}
These are the folders to see the location of my files: Folders.
This solution using npm install express#">=3.0.0 <4.0.0" --save did not work in my case. After I used it in my terminal, the same error kept showing.
How can I solve this issue?
Try this and either use express.json() or bodyParser.json()
if you go into the file node_module/express/lib/express.js you can see under module dependencies body-parser module is already imported var bodyParser = require('body-parser);
var Product = require("./model/product");
var WishList = require("./model/wishlist");
//app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post("/product", function (request, response) {
var product = new Product();
product.title = request.body.title;
product.price = request.body.price;
product.save(function (err, savedProduct) {
if (err) {
response.status(500).send({ error: "Could not save product" });
} else {
response.status(200).send(savedProduct);
}
});
});
app.listen(3000, function () {
console.log("Swag Shop API runing on port 3000...");
});
Install express.js & mongoose by typing $npm install --save
express mongoose
Type the codes below on TOP for your proper
imports and declarations
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/swag-shop');
Related
I am making a simple test for RESTApi using Node.js, mongodb and express from this article:
MERN Part I: Building RESTful APIs with Node.js and Express
but there is an error somewhere in code i can't locate. The author of article used babel but due to some other error i avoided it. Given below are code files:
App.js
var routes= require('./src/routes/userRoutes').routes
var express= require("express")
var mongoose=require('mongoose')
var bodyParser=require('body-parser')
const app = express();
const PORT=4001
// SET INDEX PAGE
app.get('/',function(req,res){
res.send(`Node and express server running on PORT ${PORT}`);
});
// START SERVER
app.listen(PORT,function(){
console.log(`Your server is running on PORT ${PORT}`);
});
// ESTABLISH ROUTES
routes(app)
// Join Database to API
mongoose.Promise= global.Promise;
mongoose.connect('mongodb://localhost/userdb', {
useNewUrlParser:true,
useUnifiedTopology:true
})
// body-parser setup
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
userModel.js : I have commented out the "required" to avoid the Validation Error and see what document is being saved in the collection.
var mongoose = require('mongoose')
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userName:{
type:String,
//required:"Enter your name",
},
UserID:{
type:Number,
//required:"Enter User ID:",
},
password:{
type:String,
// reequired:"Enter your password?",
}
});
module.exports={UserSchema}
userController.js:
var mongoose=require('mongoose')
var UserSchema = require("../models/userModel").UserSchema;
const UserModel= mongoose.model("Users",UserSchema)
const addNewUser = (req,res) => {
let newUser= new UserModel(req.body);
newUser.save((err,user) => {
if(err) res.send(err)
else res.json(user)
})
}
module.exports={addNewUser}
userRoute.js:
var addNewUser = require('../controllers/userController').addNewUser;
const routes = (app) => {
// create routes for login/signup/view
app.route('/users')
.get((req,res)=> res.send("Get request successful"))
app.route('/users/:userID')
.put((req,res)=>res.send(`Put Request succesful for ${req.params.donationID}`))
.delete((req,res)=>res.send("delete Request successful"))
.post(addNewUser);
app.route('/done')
.get((req,res)=>{
res.send("Goodbye");
process.exit(0);
});
}
module.exports={routes};
Response recieved when POST request with URI:localhost:4001/users/1?userName=Adnan&UserID=123&password=0000
{
"_id": "5fd0b07b12615110d420a91b",
"__v": 0
}
Expected Output: User Object in JSON
I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!
The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});
I'm trying to build a simple blog with a MEAN stack and I'm currently setting up the back end. I'm testing my routes with Postman and for some reason, I can't save the title and body of a post in the DB.
My model:
models/posts/db.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PostSchema = new Schema ({
title: { type: String },
body: { type: String },
date: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Post', PostSchema);
My controller: controllers/posts.index.js
var base = process.env.PWD;
var Post = require(base + '/models/posts/db.js')
var createPost = function(req, res) {
var post = new Post(req.body)
post.save(function(err, post) {
if(err) { res.sendStatus(500, err); }
res.json(post);
})
}
var getPosts = function(req, res) {
Post.find(function(err, posts) {
if (err) { res.sendStatus(500, err); }
res.json(posts);
})
};
module.exports = {
createPost,
getPosts
}
And here are my main routes in routes/index.js
router.get('/posts', posts.getPosts);
router.post('/posts/create', posts.createPost);
module.exports = router;
And my main server is using a /api endpoint:
`app.use('/api', routes);`
So in Postman, when I send a POST request to /api/posts/create with a post containing a title and a body, an empty post is stored. I get something like this inserted:
{
"__v": 0,
"_id": "5a29de91521f168eb9e1bcf2",
"date": "2017-12-08T00:36:33.280Z"
}
Any help would be appreciated.
It looks like the Post may not be getting the body of your actual post. You can fill the body property on your request with the body-parser module. Do an npm install body-parser and add this to your code:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
I figured it out, 2 problems:
The order of where you place body-parser is important, I wrote the line after setting my routes so it wasn't parsing anything.
I hadn't set up my Postman correctly, it was sending regular text instead of a JSON object. facepalm
I have 2 webservers that I have created on ports 3000 and 4000.
One of the webservers created a database and has 3 collections..
show dbs
local 0.000GB
sensor_db 0.000GB
use sensor_db
switched to db sensor_db
show collections
sensors
templategroups
templates
Can the 2nd server access this Database created ? if yes, I am not able to access the collections ..Is there any syntax to it?
1st server:
var express = require('express');
var app= express();
var path = require('path');
var bodyParser= require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
app.get('/sensorlist',function(req,res) {
console.log("I recieved a GET /sensorlist request");
Sensor.find(function(err,data){
if (err) return console.error(err);
console.log(data);
res.json(data)
});
});
app.post('/check/health',function(req,res){
socket.emit('data', 'I need your health status', function ack(data) {
console.log('data emit was acknowledged by Monitoring Server:', data);
return res.json(data);
});
});
2nd Server:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require('express');
io.on('connection', function(socket){
console.log('connection received from Provisioning');
// To get messages from Provisioning server
socket.on('data', function(data, ack) {
console.log('Message from provision is : ' + ': ' + data);
ack('here is your data - 1111');
console.log("Trying to access the Sensor_DB Database");
Sensor.find(function(err,data){
if(err) return console.error(err);
console.log(data);
//res.json(data);
});
});
});
server.listen(4000, function(){
console.log('socket.io server listening on *:4000');
});
I get error - Sensor is not defined
Much Thanks
Jessi
I tried to dispay the collections once its connected to the DB but get this error message : Cannot read property 'hasListCollectionsCommand' of null
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/sensor_db') ;
console.log("successfully connected to the database");
//mongoose.connection.db
mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
Two Different servers cannot share the same instance of the sensor object.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
This code declaring the schema for one server not for the second . so you have to declare the instance in the second server also.
Issue not with the mongo data base issue is the sensor instance that is not have any declaration in second server.
I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong