I'm learning to create a RESTful API using Node and Express 4.0 and am having trouble just getting the POST req to work properly when tested with Postman in Chrome. The request times out when the save method is called (I think--I'm new to this).
Here's my base code:
server.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
mongoose.connect('mongodb://node:node#ds033484.mongolab.com:33484/testdatabase');
var Dog = require('./app/models/dog');
var router = express.Router();
router.route('/dogs')
.post(function(req, res) {
var dog = new Dog();
dog.name = req.body.name;
dog.save(function(err) {
if (err)
return res.send (err);
res.json({ message: 'Dog created!' });
});
});
app.use('/api', router);
app.listen(port);
console.log('Code is testable on port ' + port);
app/models/dog.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DogSchema = new Schema({
name: String
});
module.exports = mongoose.model('Dog', DogSchema);
I tested the code with Postman, selecting POST from the dropdown menu and selecting x-www-form-urlencoded from the Body tab. I filled in the key (name) and the value "Clifford."
The request timed out.
So I added a few console logs to server.js:
router.use(function(req, res, next) {
console.log('Router is in use.');
next();
});
router.route('/dogs')
.post(function(req, res) {
console.log("Accessing Mongoose.");
var dog = new Dog();
console.log("New dog.");
dog.name = req.body.name;
console.log("The dog is named: " + dog.name);
dog.save(function(err) {
if (err)
return res.send (err);
res.json({ message: 'Dog created!' });
});
});
All of them show up, including "The dog is named: Clifford". As far as I can tell, that means it's a problem with the save method.
What should I be doing next? Any help would be much appreciated. I found a similar problem here: no req.body sent on POST requests
But OP here seems to just be using the wrong settings in his test and gets an error. The only error I get is the timeout.
It will work if you replace
router.route('/dogs').post(function(req, res) {});
by
app.post('/dogs', function(req, res) {});
By the way, if you're looking for a more efficient way to debug your node server than console.log(), I recommend node-inspector.
Related
This is my current code:
const mongoose = require("mongoose")
const params = new URLSearchParams(window.location.search)
module.exports = (req, res) => {
res.send({
creatorid: "",
whitelisted: false
})
}
At the moment, it is giving me the error: window is not defined. I have no idea why. Can someone help please?
As it was mentioned above. There is no window object in Node enviroment.
If you are using Express
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});
app.listen(3000);
Also check out this and this thred
I have been doing a project in URL shortening and i am getting an undefined as a result to get request.
Also i get a blank page too as result,but according to my knowledge everything is ok,i can't figure out what is the mistake
Here's my code(please check the app.get section)
'use strict';
var bodyParser = require('body-parser')
var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var http = require("http");
var cors = require('cors');
const dns = require('dns');
var app = express();
// Basic Configuration
var port = process.env.PORT || 3000;
/** this project needs a db !! **/
// mongoose.connect(process.env.DB_URI);
app.use(cors());
/** this project needs to parse POST bodies **/
// you should mount the body-parser here
app.use('/public', express.static(process.cwd() + '/public'));
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/views/index.html');
});
// your first API endpoint...
app.get("/api/hello", function (req, res) {
res.json({greeting: 'hello API'});
});
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
var saveSchema = new mongoose.Schema({
name: String,
url: Number,
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
/** 3) Create and Save a Person */
var SaveData = mongoose.model('Save', saveSchema);
//**Here's the start of my problem,i think**
app.get("/api/shorturl/:id1",function(req,res){
SaveData.find({url:1},function(err,data){ console.log(data.name)//**i am getting undefined for this in console**
res.json(data.name);})
});
app.post("/api/shorturl/new",(req,res)=>{
var body=req.body.url;
dns.lookup(body,(err,data)=>{
var new2= new SaveData({name:body,url:1});
new2.save((err,data)=>{res.json(new2);});
})
});
app.listen(port, function () {
console.log('Node.js listening ...');
});
I checked my DB whether the schema data is inputted or not, it is getting inside DB, so retrieval makes the problem I think.
mongoose.model.prototype.find returns an array of objects found. If you type Array.prototype.name in a console somewhere, you'll get undefined. Instead, use mongoose.model.prototype.findOne.
Your enviorment variables are working? I notice you're not using dotenv module or something like that to configure your process.env.
I am trying to make a post request to my first app, but every time I go to make the post, it gives me this error: TypeError: db.getConnection is not a function
I have tried all of stack overflows suggestions, but I still can't seem to get it to work after messing around with the code for the last 2 days. I am a beginner so please forgive me, but here is what my code looks like...
my db.js looks like this....
var mysql = require('mysql');
var mainDb = mysql.createPool({
host : process.env.mysql_host,
user : process.env.mysql_user,
password : process.env.mysql_pwd,
database : process.env.mysql_db
});
exports.getConnection = function(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
});
};
and my register.js code looks like this...
var express = require('express');
var router = express.Router();
var db = require(__dirname, 'models/db');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
router.get('/register', function(req, res, next) {
res.render('register', { title: 'Register for a free account' });
});
router.post('/register', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var today = new Date();
var users = {
"username": req.body.username,
"email":req.body.email,
"password":req.body.password,
"created":today,
"modified":today
};
db.getConnection(function(err, connection) {
connection.query('INSERT INTO users SET ? ', users, function(err, result) {
connection.release();
if (err) { return console.error(err); }
});
});
res.redirect('/index');
});
module.exports = router;
I don't know if my app.js is relevant for this question, but it looks like this...
const express = require('express');
http = require('http');
path = require('path');
session = require('express-session');
app = express();
mysql = require('mysql');
bodyParser = require('body-parser');
db = require(__dirname, 'models/db')
var index = require('./routes/index');
var register = require('./routes/register');
app.use('/', index);
app.use('/', register);
var engine = require('ejs-mate');
app.engine('ejs', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
var server = http.createServer(app);
var port = 8995;
server.listen(port);
module.exports = app;
When I start app.js I get no errors, only when I make my post request from my form, the error shows up in my browser. Please help!
At db.js you are exporting only a function. But at register.js, you are trying to use db as if it was an object.
To solve your problem, at db.js, just export an object, instead of a function:
function getConnection(callback) {
mainDb.getConnection(function(err, connection) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
callback(err, connection);
}
module.exports = { getConnection };
You don't need use getConnection method only exports the pool, according the documentation.
https://github.com/mysqljs/mysql
Im just starting out with MEAN application, and im stuck while adding data into the database. So please help me to find the solution for this.
This is the root file, entry point in the application
//Importing modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');
var app=express();
const route=require('./routes/route');
//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
mongoose.connection.on('connected',()=>{
console.log("Successfully established a connection to mongodb Database ")
});
//on error
mongoose.connection.on('error',(err)=>{
if(err){
console.log("Failed to established a connection "+err);
}
});
const port=3000;
//For routing
app.use('/api',route);
//Adding middleware -cors
app.use(cors());
//body-parser
app.use(bodyparser.json());
//Static Files
app.use(express.static(path.join(__dirname,'public')));
//port no
app.get('/',(req,res)=>{
res.send('Foobar');
});
app.listen(port,()=>{
console.log("Server started listening to port "+port);
})
And this my route file,
const express = require('express');
const router = express.Router();
// fetching the schema
const Contact = require('../Models/contacts');
//Retriving the contacts
router.get('/contacts', (req,res,next)=>{
Contact.find(function(err,contacts){
// Sending to client in json format
res.json(contacts);
});
});
// Adding Contacts
router.post('/contact', (req,res,next)=>{
let newContact = new Contact({
first_name : req.body.first_name,
last_name : req.body.last_name,
phone : req.body.phone
});
newContact.save((err,contact)=>{
if(err){
res.json({msg: "Failed to add contact."});
}else{
res.json({msg:"Contact added sucessfully"});
}
});
});
//Deleteing contact
router.delete('/contact/id',(req,res,next)=>{
Contact.remove({_id:req.params.id},function(err,result){
if(err){
res.json(err);
}else{
res.json(result);
}
})
});
module.exports=router;
Now, I'm trying to add a few records in DB (Mongo DB) using postman, but it's throwing an error saying "TypeError: Cannot read property 'first_name' of undefined, at router.post (C:\Mean App\ContactList\routes\route.js:16:25)"
In postman, for header, I'm using "Content-type: application/json" and in raw body, I'm adding JSON data like this,
{
"first_name" : "Siddhesh",
"last_name" : "Mishra",
"phone" : "9594106324"
}
And here is my code where I'm creating schema
const mongoose=require('mongoose');
const ContactSchema = mongoose.Schema({
first_name:{
type:String,
required:true
},
last_name:{
type:String,
required:true
},
phone:{
type:String,
required:true
}
});
const Contact=module.exports=mongoose.model('Contact',ContactSchema);
thank you.
You will have to move body-parser above the routes use and should work
//body-parser
app.use(bodyparser.json());
//For routing
app.use('/api',route);
From Express API v4.x
app.use([path,] callback [, callback...])
...
Middleware functions are executed sequentially, therefore the order of
middleware inclusion is important.
body-parser needs to go before the routes:
//Importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//Connect to mongoDb
mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
mongoose.connection.on('connected', () => {
console.log("Successfully established a connection to mongodb Database ")
});
//on error
mongoose.connection.on('error', (err) => {
if (err) {
console.log("Failed to established a connection " + err);
}
});
const port = 3000;
//body-parser
app.use(bodyparser.json()); // here
//Adding middleware -cors
app.use(cors());
//Static Files
app.use(express.static(path.join(__dirname, 'public')));
// For routing
app.use('/api', route);
app.get('/', (req, res) => {
res.send('Foobar');
});
app.listen(port, () => {
console.log("Server started listening to port " + port);
})
To always be on the safe side your routes should always come last after all middleware.
I have this very simple code that stores superhero name and power to database.
All connections work normally. When i ran mongod i used --dbpath C:/nodeprojects/sankarit/data. I have tried change the path like 50 times with different paths.
So my code sends nimi and supervoima (name, superpower) from client side and it tries to add them to database but literally nothing happens in db. When i write console.log("yay it works") on save function, it says that its working. And if i console log superhero it seems to work normally.
Here is client side:
$http.post("api/juttu", {nimi: "besthero", supervoima: "whiskey"}).success(function(response){
console.log(response.data);
}).error(function(){
console.log("Error")
})
Here is my server.js:
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.set('debug', true);
// SANKARI SCHEMA
var Sankari = require('./app/models/sankarit');
// CONTROLLERIT
var testCtrl = require('./server/testCtrl');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use('/public', express.static(__dirname + '/public'));
// DB conn
// I have tried with /test, /heros, /sankariKanta, /sankarit
mongoose.connect('mongodb://127.0.0.1:27017/test');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
//PORTTI
var port = process.env.PORT || 8080;
// ROUTER
var router = express.Router();
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.post("/api/juttu", testCtrl.juttu);
app.listen(port);
Here is the testCtrl:
var Sankari = require("../app/models/sankarit");
module.exports.juttu = function (req, res){
// Tried also var uusiSankari = new Sankari(req.body);
var uusiSankari = new Sankari();
uusiSankari.nimi = req.body.nimi;
uusiSankari.supervoima = req.body.supervoima;
uusiSankari.save(function(err){
if(err){
console.log(err);
} else{
// This is always showing up
console.log("This is working!");
}
});
};
Also when i try console.log(req.body); It is working correctly.
Here is schema(sankarit.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = ({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);
When i run the program, the mongoose debug thing says:
Mongoose: sankaris.insert({ __v: 0, _id: ObjectId("57ff0a649dbf169c15000001"), nimi: 'besthero', s
upervoima: 'whiskey' }) {}
So when i debug and console log everything the program does it seems to work like dream. I have made these MEAN stack tutorials like 5-10 and everytime database worked normally. This is first time i'm trying to make whole code by myself. I tried solve this whole night but i didn't get absolutely anywhere.
You forgot to use the Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = Schema({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);