I am self learning nodeJS, Now I tried to insert data in MongoDB and this my goal
insert values in here and once submit button is clicked, should save the data successfully to mongodb and this should return a successful message.
But this is the error
TypeError: Cannot read property 'location' of undefined
Here are the code snippets
const express = require('express');
const dotenv = require("dotenv").config();
const address = process.argv[2];
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const app = express();
//INSERT TO MONGO DB
//connect to mongo db
mongoose.connect('mongodb://localhost/weathertest2');
mongoose.Promise = global.Promise;
//create weather schema
const WeatherSchema = new Schema({
location:{
type: String
},
temperature:{
type: String
},
observationTime:{
type: String
}
});
const Weather = mongoose.model('weather', WeatherSchema);
// post request
app.post('/new', function(req, res){
new Weather({
location : req.body.location,
temperature: req.body.temperature,
observationTime : req.body.observationTime
}).save(function(err, doc){
if(err) res.json(err);
else res.send('Successfully inserted!');
});
});
// listen for request
app.listen(process.env.port || 9000, function(){
console.log('now listening for testing request');
});
app.use(express.static('public'));
Try using the body-parser middleware alongside with express:
https://www.npmjs.com/package/body-parser
const bodyParser = require("body-parser");
/*
* Parses the text as URL encoded data (which is how browsers tend to send
* form data from regular forms set to POST) and
* exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({ extended: true }));
This way the data from the form should be included in the request body (req.body.location)
It seems that the body of the request is undefined. This might be because express isn't parsing the request body correctly. The solution is probably to use a body parser.
npm install --save body-parser
Then import body-parser into your file:
const bodyParser = require('body-parser')
Then place this line before the "/new" handler:
app.use(bodyParser)
Related
I am implementing a simple signup / login functionality in node js
But when using postman to post the router to localhost:3000/api/chatapp/register i am gettig error message
Cannot POST /api/register
CODE:
server.js
const express=require('express');
const mongoose=require('mongoose');
const cookiePaser=require('cookie-parser');
// const logger=require('morgan');
const app=express();
const dbConfig= require('./config/secret');
//adding middleware
app.use(cookiePaser()); //save our token in the cookie
// app.use(logger('dev')); // to display the url and http status code in the console
mongoose.Promise = global.Promise;
mongoose.connect(
dbConfig.url,{useNewUrlParser: true, useUnifiedTopology: true}
);
const auth=require('./routes/authRoutes');
app.use(express.json({limit: '50mb'})); //data coming in from form is limited up to 50 mb size
app.use(express.urlencoded({ extended: true, limit:'50mb'}));
app.use('/api/chatapp',auth);
app.listen(3000, () => {
console.log('Running on port 3000');
})
authRoute.js
const express=require('express');
const router=express.Router();
const AuthCtrl=require('../controllers/auth');
router.post('/register',AuthCtrl.CreateUser);
module.exports=router;
auth.js
module.exports={
CreateUser(req,res){
console.log(req.body);
}
};
userSchema.js
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
username: { type: String },
email: { type: String },
password: { type: String },
});
module.exports=mongoose.model('User',userSchema);
nodemon server and mongod are running fine
Postman result
for further details kindly look into my github repo :
https://github.com/Umang01-hash/chatApp-backend
Are you sure if that's the correct endpoint? Check out the folder structure and see this image for your answer.
I'm coding up a simple demo rest-api, the default /api route work just fine, returning all the results(image below), but I'm hitting a roadblock. Which is that when I type: http://localhost:5050/api/interpol where
/interpol maps to api/:params I'm getting back an empty array, instead of the document matching the artist.
As a side note, I'm running a 32bit Ubuntu 14.04(didn't realize it till after), so I had to downgrade both mongodb and mongoose to get them working together, as a consequence I'm using Mongodb 2.2.6 & Mongoose 4.0.8. Thanx in advance.
Model
// Dependencies
const mongoose = require('mongoose');
//Mongoose Schema
const Albums = new mongoose.Schema({
title : { type: String },
releaseYr : { type: Date }
});
const MusicSchema = new mongoose.Schema({
artist : { type: String },
albums : [Albums]
});
mongoose.model('Music', MusicSchema);
module.exports = mongoose.model('Music');
Router
// Dependencies
const express = require('express');
const Music = require('../models/musicModel');
const musicRouter = express.Router();
// Routes
musicRouter.get('/', (req, res) => {
Music.find({}, (err, artists) => {
res.json(artists)
})
});
musicRouter.route('/:artistName').get((req, res) => {
const artistName = req.params.artistName;
Music.find({ artist: artistName }, (err, artist) => {
res.json(artist)
});
});
module.exports = musicRouter;
App
// Dependencies
const express = require('express'),
bodyParser = require('body-parser'),
Mongoose = require('mongoose'),
Joi = require('joi');
// Initiate express
const app = express();
// Import musicRouter to handle api routes
const musicRouter = require('./api/musicRouter');
// Downgraded to Mongodb 2.2.6 & Mongoose 4.0.8
// Connect to Mongo database via Mongoose
Mongoose.connect('mongodb://localhost:27017/music1', {useNewUrlParser: true});
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Send routes to musicRouter
app.use('/api', musicRouter);
module.exports = app;
As with all JavaScript, Mongodb does a case-sensitive search.
You're querying { artist: 'interpol' } But referring from the image, you've saved it as Interpol.
So either send your request as /api/Interpol or make a case-insensitive search using regex as detailed here
Making this simple Node.js Express API I encountered an odd problem:
I am creating a model and inserting data into it and then saving it to my MongoDB. But the record is never saved but I also don't get any error. I have checked if MongoDB is running and both syslog for Node errors and mongod.log for MongoDB errors as well as my own Wilson debug.log file. All contain no errors.
I use postman to test the API and do get a response every time. It's just that the data does not get saved to MongoDB (I used the mongo console with db.collection.find() to check for inserted records).
Any idea why this could be happening?
my code:
api.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var https = require('https');
var fs = require('fs');
var winston = require('winston');
// Configure logging using Winston
winston.add(winston.transports.File, { filename: '/home/app/api/debug.log' });
winston.level = 'debug';
// Request body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Enable https
var privateKey = fs.readFileSync('path to private key');
var certificate = fs.readFileSync('path to cert file');
var credentials = {
key: privateKey,
cert: certificate
};
// ROUTERS
var router = express.Router();
var speciesRouter = require('./app/routes/speciesRouter');
router.use('/species', speciesRouter);
// Routes prefix
app.use('/api/v1', router);
// SERVER STARTUP
http.createServer(app).listen(3000);
https.createServer(credentials, app).listen(3001);
speciesRouter.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var Sighting = require('../models/sighting');
var winston = require('winston');
// Database connection
var dbName = 'dbname';
mongoose.connect('mongodb://localhost:27017/' + dbName);
var db = mongoose.connection;
db.on('error', function(err){
winston.log('debug', err);
});
router.route('/')
.post(function(req, res) {
var sighting = new Sighting();
sighting.user_key = req.body.user_key;
sighting.expertise = req.body.expertise;
sighting.phone_location = req.body.phone_location;
sighting.record_time = req.body.record_time;
sighting.audio_file_location = '/var/data/tjirp1244123.wav';
sighting.probable_species = [{species_name:'Bosaap', percentage:100}];
var error = '';
winston.log('debug', 'test');
// This does not get execute I suspect..
sighting.save(function(err) {
winston.log('debug', 'save');
if (err) {
winston.log('debug', err);
error = err;
}
});
res.json({
probable_species: probable_species,
expertise: req.body.expertise,
error: error
});
});
module.exports = router;
sighting.js (model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SightingSchema = new Schema({
user_key: String,
expertise: Number,
phone_location: { lat: Number, lng: Number },
record_time: Number,
audio_file_location: String,
probable_species: [{ species_name: String, percentage: Number }]
});
module.exports = mongoose.model('Sighting', SightingSchema);
Did you try updating your mongodb.
sudo npm update
You can try using promise.
return sighting.save().then(function(data){
console.log(data); // check if this executes
return res.json({
probable_species: probable_species,
expertise: req.body.expertise,
error: error
});
}).catch(function(err){
console.log(err);
});
One more thing dont use res.json outside the save function because in async code it will run without waiting for save function to complete its execution
I am trying to post data from my react. Backend - express.
Here is backend code:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");
mongoose.connect("mongodb://localhost/blog-react");
//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));
//schema config
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
//it should be date. With default value now.
created: {
type: Date, default: Date.now
}
});
var Blog = mongoose.model("Blog", blogSchema);
function handle500(response, error){
console.log(error.stack);
response.status(500);
response.json({error: "error: internal server error"});
}
app.post("/api/blogs", function(request, response){
var blog = {
title: request.sanitize(request.body.title),
image: request.sanitize(request.body.image),
body: request.sanitize(request.body.body)
};
console.log(request.body);
Blog.create(blog, function(error, newBlog){
if(error){
console.log("inside post handler ERROR")
handle500(response, error);
}
else{
console.log("inside post handler OK")
response.json({status: "success"});
}
});
});
React code:
var requestUrl = "/api/blogs";
var blog = {
title: "a",
image: "b",
body: "c"
}
axios.post(requestUrl, blog)
.then(function(response){
console.log("success",response.data)
})
.catch(function(response){
console.log("error", response);
});
When I post data via axios - request.body is always {}
But if I post data via regular form - all is correct - request.body contains all expected data.
What am I doing wrong with axios?
You are missing one middleware, bodyParser.json(). Add it to your configuration.
mongoose.connect("mongodb://localhost/blog-react");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));
For people using Express>=4.16, bodyParser has been changed to the following:
app.use(express.json());
For me the issue was valid JSON format including double quotes on the variables.
This did not work
const res = await axios.post(serverPath + "/user/login", {
email: email,
password: password,
});
This DID work (with double quotes around email and password)
const res = await axios.post(serverPath + "/user/login", {
"email": email,
"password": password,
});
It looks like you only have two points left to make it work :
one : the http method should be set to POST instead of GET since you want to send something.
two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`
On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.
I suppose your server is using express, here is how you will do it with express :
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */
I am trying to post data to a mongo DB through a URL of a browser. I was able to get it working using only expressJS, but I am having difficulty getting it working with mongodb. I'm still very new to this, so I am hoping that I am just missing a simple component and that I am at least on the right track.
When I enter "http://localhost:27017/api/users?id=4&token=sdfa3" or "http://localhost:27017/nodetest5/api/users?id=4&token=sdfa3" into the url, I'd like to see "4 sdfa3" on the webpage. Right now I am just getting a webpage with the message: "It looks like you are trying to access MongoDB over HTTP on the native driver port."
Here is my server.js file:
// packages
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');
//db stuff
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest5');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded
//make accessible mongo db accessible to router
app.use(function(req, res, next){
req.db = db;
next();
})
// routes
app.get('/api/users', function(req, res) {
//get values from URL
var id = req.param('id');
var token = req.param('token');
res.send(user_id + ' ' + token + ' ');
});
// POST to localhost
// parameters sent with
app.post('/api/users', function(req, res) {
//internal DB value
var db = req.db;
//values from URL
var user_id = req.body.id;
var token = req.body.token;
//set collection
var collection = db.get('usercollection');
//Submit to DB
collection.insert({
"id" : id,
"token" : token
}, function (err, doc){
if (err) {
res.send("Error encountered when trying to add entry to database.");
}
else {
res.send(user_id + ' ' + token + ' ');
}
});
});
Thank you!
The HTTP interface for MongoDB can be accessed via port number 28017. You'll need to provide the --rest option to mongod:
`$ mongod --rest`
You can read more in the HTTP Interface documentation.
You should exercise caution when using the HTTP interface. From the MongoDB documentation:
WARNING
Ensure that the HTTP status interface, the REST API, and the JSON API are all disabled in production environments to prevent potential data exposure and vulnerability to attackers.