can't create a new directory using mongoose and express - javascript

Like the title entails.
I'm trying to make an application that when i put in certain info, it creates a link using mongoose _id. and express's app.get what i don't get is that to be able to join that directory i have to reload the whole server, which for the users and my sake a i don't want to do.
var mongoose = require("mongoose");
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var router = express.Router();
app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
mongoose.connect("mongodb://localhost:27017/NEW_DB1");
console.log("Connection to database has been established");
var collectedData = new mongoose.Schema({
ipAddress: String,
name: {
type: String,
unique: false
}
});
var collectionOfData = mongoose.model("dataType", collectedData);
io.on("connection", function (socket) {
socket.on("name", function (e) {
var ip = socket.request.socket.remoteAddress;
var dataBase = mongoose.connection;
var Maindata = new collectionOfData({
ipAddress: ip,
name: e
});
Maindata.save(function (err, Maindata) {
if (err) {
return console.error(err);
} else {
console.dir(Maindata);
}
});
});
});
app.get("/mix", function (req, res) {
collectionOfData.find(function (err, data) {
res.send(data);
});
});
collectionOfData.find(function (err, data) {
data.forEach(function (uniqueURL) {
app.get("/" + uniqueURL._id, function (req, res) {
res.send("<h1>Hello " + uniqueURL.ipAddress + "</h1><p>" + uniqueURL.name + "</p>");
});
});
});
http.listen(10203, function () {
console.log("Server is up");
});
So what i'm trying to do is make it so i don't have to reload the whole server, and i'm able to just join the created directory when it's done being loaded.
figured i should put a quick example:
localhost:10203/55c2b2f39e09aeed245f2996
is a link a user just created the long
55c2b2f39e09aeed245f2996
is the effect of the _id, but when the user try's to connect to that site it won't work until i reload the server and obviously i'd like to avoid that haha.
I have a index.html file, but all that has is a socket.emit that sends "name" to the server

app.get("/", function (req, res) {
var ip = req.connection.remoteAddress;
res.sendFile(__dirname + "/index.html");
});
app.get('/:uniqueURL', function(req, res){
var id = req.params.uniqueURL;
res.send("Your requested id : " + id);
})
Try to use this above.
You are creating fix get path inside collectionData.find. That is the problem. So each time you have to reload the server by restarting.

Related

How to set two root endpoints in one file Restful API with node.js & EXPRESS

I have root endpoint who work when users enter the url like this:
http://localhost:8000/?date=2019-10-20&station=41027&daysForward=3
I want to create second root endpoint in the same file with different query but that did not work.
My code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
var con2 = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
let aladinModel= '';
let aladinModelStations = '';
app.route('/')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
const date = req.query.date;
const station = req.query.station;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram('${date}', ${station}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({aladinModel})
} catch(error){
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM stations_cells`;
con2.query2(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({aladinModelStations})
} catch(error){
console.log("Error query database!!!");
}
});
app.use(function(req, res){
res.status(404);
});
I guess this is not the right way to route pages but I hope someone can explain to me with an example how I could fix the code - so when a user enters:
http://localhost:3000/stations
the data should be loaded.
I see this error when I try to open this link.
[nodemon] starting `node server.js localhost:8000`
Server running on port 8000
Error query database!!!
This query
SELECT station, ime
FROM stations_cells
on the second root point is fine. I try to SELECT with HeidiSQL and database return the data values ?
Where is the problem for the second root point ?
That might not be the case, but here's the suggestion (which doesn't fit in comment section)
app.route('/')
.get(function(req, res) {
// omitted
});
app.route('/stations')
.get(function(req, res) {
// omitted
});

Can't post param id in NodeJS server on Express

I'm currently developing an Ionic application and writing the server in NodeJS with Express and hosting it on Heroku. However, it doesn't correctly post the desired route. I get this error when I test it on Chrome:
Failed to load resource: the server responded with a status of 404 (Not Found) https://[SERVER NAME].herokuapp.com/rooms//messages
The server should be posting the id parameter in between /rooms/ and /messages/, but it isn't. Here's the server-side code:
var messages = []; //make an array to hold messages
var rooms = [];
app.get('/rooms', function(req, res) {
res.json(rooms);
});
app.get('/rooms/:id/', function(req, res){
var room = rooms[req.params.id];
res.json(room);
});
app.post('/rooms', function(req, res) {
var newRoom = {
timestamp: new Date()
//username: req.body.username
};
rooms.push(newRoom);
res.json(rooms);
console.log(rooms);
});
app.get('/messages', function(req, res) { //req = request, res = response
res.json(messages);
});
app.get('/messages/:id', function(req,res) {
var message = messages[req.params.id];
res.json(message);
});
app.post('/messages', function(req,res){
var newMessage = {
message:req.body.message,
username:req.body.username,
timestamp: new Date()
};
messages.push(newMessage);
res.json(messages);
});
Why isn't it properly posting the correct route? When I check the logs on Heroku it does not appear to be getting the :id for the rooms.
Thank you.
EDIT: Here are the github repos for further reference:
Client: https://github.com/dukeeagle/ttt-client
Server: https://github.com/dukeeagle/ttt-server
I fixed it!
Here's the correct routing method for those who are interested:
app.get('/rooms', function(req, res) { //req = request, res = response
var user = users[req.params.id];
var userRooms=[];
res.json(rooms);
});
app.get('/rooms/:id', function(req,res) {
var room = rooms[req.params.id];
res.json(room);
});
app.post('/rooms', function(req,res){
var newRoom = {
name:req.body.name,
id:rooms.length,
username:req.body.username,
timestamp: new Date(),
messages: [],
players: []
};
rooms.push(newRoom);
res.json(rooms);
});
app.post('/rooms/:id/messages', function(req, res){
var room = rooms[req.params.id];
var newMessage = {
username:req.body.username,
timestamp: new Date(),
message: req.body.message
}
room.messages.push(newMessage);
res.json(room);
});
app.post('/rooms/:id/players', function(req, res){
var room = rooms[req.params.id];
var newPlayer = {
timestamp: new Date(),
player: req.body.username
};
room.players.push(newPlayer);
res.json(room);
});
I init express server with that code:
var express = require('express');
var app = express();
app.get('/rooms/:id/messages', function (req, res) {
var id = req.params.id;
res.send('Hello, moto! ' + id);
});
app.listen(2345, function () {
console.log('server started');
});
When I navigate to http://localhost:2345/rooms/123/messages I see at the page string Hello, moto! 123
Try to remove your other routes for tests, maybe it is get some conflicts.

Node.js passing parameters to client via express render

I'm using Node.js and I'm having issues communicating with a client.
I define Express:
var express = require("express");
var app = express();`
When I try and pass a parameter to the client upon requesting a page the variable holds no data, for example:
app.get("/", function(req, res){
res.render("index", { name: "example" });
});
On the index page, when I use the console to print the variable (name)it returns "".
More info: http://expressjs.com/api.html#app.render
Am I missing something or doing something wrong?
The variable name you sent to the render function is only available while rendering the page, after it is sent to the client, it is not accessible. You have to use it in your view on the rendering stage.
Since you are using handlebars, you can display it in your page like this, for instance:
<h1>{{ name }}</h1>
If you want to use this data in a javascript, use it inside a script tag:
<script>
var name = "{{ name }}";
console.log(name);
</script>
You are basically telling express to render your index page and providing a value for the name variable, but that doesn't necessarily make the name var available in your client side javascript. You need to edit your index template to display the name variable in the page.
The syntax varies depending on the templating engine you are using (jade, ejs, dustjs).
Another solution is to use an ajax call in your client page's javascript and use res.json on the server instead to send the data. Then you can evaluate name in the console. Ex using jquery:
index.html:
$.get( "/getvar", function( data ) {
name = data.name;
});
server.js:
app.get("/getvar", function(req, res){
res.json({ name: "example" });
});
If you want to get parameters on the clientside via javascript, you should do template like this <script>var data = data</script>, otherwise variables aren't available
If you use Jade, it will be something like this:
script(type='text/javascript').
var name = !{name}
Passing data list from node js to html
server.js
var http = require('http');
var express = require('express');
var sqlite3 = require('sqlite3').verbose();
var bodyParser = require('body-parser');
var path = require("path");
console.log('Server running at http://127.0.0.1:8081/');
var __dirname = "D:/html-files";
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var engine = require('consolidate');
app.engine('html', engine.mustache);
app.use(express.static('./'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
});
app.post('/get-user-list', urlencodedParser, function (req, res) {
let db = new sqlite3.Database('user.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the user database.');
console.log("ID" + "\t" + "NAME" + "\t" + "EMAIL");
});
db.serialize(() => {
var dataList = "";
db.each('SELECT id, name, email FROM USER ', (err, row) => {
if (err) {
console.error(err.message);
}
if(dataList != "")
dataList = dataList + ',';
dataList = dataList + '{"id":"' + row.ID + '","name":"' + row.NAME + '","email":"' + row.EMAIL + '"}';
console.log("dataList : " + dataList);
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Close the database connection.');
response = {'username':dataList};
aFunction(res, dataList);
});
});
});
var aFunction = function(res, dataList) {
console.log('return to page.');
console.log("dataList : " + dataList);
res.render(__dirname + "/list-all-users.html", response);
};
app.listen(8081, '127.0.0.1')

not able to store the data to mongoDB

I am trying since 3 hours to store the data from html form to mongodb using noddejs.
while clicking on submit it shows another page which returns the data which has been submitted in json format but it is not being stored in database.
This is my app.js:
app.use(serveStatic(__dirname+"/index.html")).listen(8080);
var mongoUri = 'mongodb://localhost/test';
//Note that I am changing the dbname and trying to store data in different //db will also shows the same error
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database at ' + mongoUri);
});
console.log("connection successfull");
app.use(express.bodyParser());
app.use(express.static(__dirname + "/" ));
app.use(bodyParser.urlencoded({extended:true}));
app.post('/InquiryDetails', function(req,res){
res.json(req.body);
console.log(req.body);
});
require('./models/InquiryDetails');
app.listen(4000);
console.log('Listening on port 4000...');
this is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myskyllSchema = new Schema({
name: String,
email: String,
state: String,
country: String,
school: String,
profession: String,
phone: Number
});
mongoose.model('InquiryDetails', myskyllSchema);
This is my controller:
var mongoose = require('mongoose'),
InquiryDetails = mongoose.model('InquiryDetails');
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
Any help will be appreciated.
Just replace the code in app.js :
app.post('/InquiryDetails', function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
res.send(req.body);
});
});
instead of :
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
The reason is controller was unable to load and method add is not registered with post method. Now it is working.

Parsing nested JSON using body-parser and express

I have an iOS app which is sending a JSON packet to a webserver. The webserver code looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log("MongoDB connection is open.");
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
X: Number,
Y: Number,
Orientation: Number,
UserID: String,
Time: String
});
// Mongoose Model definition
var LocationsCollection = mongoose.model('locations', LocationSchema);
// create application/json parser
var jsonParser = bodyParser.json();
// URL management
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
console.log(req.body);
}
});
// Start the server
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('App listening at %s:%s',host, port)
});
The key part is the app.post method which processes the incoming http request being sent from my iOS app. At the moment, the method which prints the req.body to the console looks like this:
{
datapoint_1:
{ timestamp: '2015-02-06T13:02:40:361Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 271.3345946652066 },
datapoint_2:
{ timestamp: '2015-02-06T13:02:40:961Z',
x: 0.6164286615466197,
y: -0.6234909703424794,
id: 'B296DF8B-6489-420A-97B4-6F0F48052758',
orientation: 273.6719055175781 }
}
So, you can see the request is a nested JSON object. Ideally, I'd like to loop through the request objects (ie. the datapoints) and insert those into the mongoDB database (via mongoose). However, I can't seem to figure out how to do much of anything with the req.body. I can't seem to create a loop to iterate through the request or how to properly parse the nested JSON file so it matches the mongoose schema. Can anyone provide some guidance on how to insert these datapoints into the mongoose database?
Set body-parser's extended property to true to allow parsing nested objects.
var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
Answering my own question. But, after figuring out how to access the key/value pairs inside the nested JSON object... it became relatively easy to figure out the rest. The updated app.post function now looks like this:
app.post('/update', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
else {
for(var datapoint in req.body){
//create new instance of LocationCollection document
var point = new LocationsCollection({
X:Number(req.body[datapoint]["x"]),
Y:Number(req.body[datapoint]["y"]),
Orientation:Number(req.body[datapoint]["orientation"]),
Time:req.body[datapoint]["timestamp"],
UserID:req.body[datapoint]["id"]
});
//insert the newly constructed document into the database
point.save(function(err, point){
if(err) return console.error(err);
else console.dir(point);
});
}
}
});
I can test if this worked by putting the following method inside the callback function once the mongodb connection is first established:
//Find all location points and print to the console.
console.log("Searching for all documents in Location Points Collection");
LocationsCollection.find(function(err,data){
if(err) console.error(err);
else console.dir(data);
});
This will print any documents that have been previously added to the database. Hopefully this helps.
Try somthing like this.
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:1024*1024, verify: function(req, res, buf){
try {
JSON.parse(buf);
} catch(e) {
res.send({
error: 'BROKEN_JSON'
});
}
}}));
It should be a simple for (var key in obj) loop:
app.post('/update', jsonParser, function (req, res) {
var locationObject = req.body(),
insertObjects = [],
key;
for (key in locationObject) { // loop through each object and insert them into our array of object to insert.
insertObjects.push(locationObject[key]);
}
if (!insertObjects.length) { // if we don't have any object to insert we still return a 200, we just don't insert anything.
return res.status(200).send({
success: true,
message: 'Nothing inserted, 0 locations in POST body',
count: 0;
});
}
LocationsCollection.create(insertObjects, function (err, res) {
if (err) {
return res.status(400).send({
success: false,
message: err.message
});
}
// we have successfully inserted our objects. let's tell the client.
res.status(200).send({
success: true,
message: 'successfully inserted locations',
count: insertObjects.length;
});
});
});
Mongo allows for inserting multiple documents with a single callback, which makes this a lot easier.
This also checks the schema to ensure only proper documents are created.

Categories