Unable to get id from the URL using params - javascript

I'm new to Express JS and MongoDB so please go easy on me.
I'm following a tutorial of web development by colt steele. here is my code
app.get("/:id",async(req,res)=>
{
const id= req.params['id'];
console.log(id);
const students= await Student.findById(id);
console.log(students);
res.render("studentdata/show",{students});
})
I'm trying to get the id using req.params but it is returning favicon.ico .
This is the error I got
error screenshot
I tried using params['name'] (name field refers to student name in DB) which worked without any error. I also tried using _id which gave me another error. I'm expecting params['id'] to return the id of the entry.

I am Assuming that you are developing your application in localhost.
Its always a best practice to keep your backend stuffs seperate.
Instead of giving the route path as app.get('/:id') you could have used
app.get('/api/:id',async(req,res) =>{
const id= req.params['id'];
console.log(id);
const students= await Student.findById(id);
console.log(students);
res.render("studentdata/show",{students});
})
And the url for this should be like this :
http://localhost:port_number/api/student_id
Here port number should be replaced with the port number on which your server is running . For example - 5000
And student_id should be replaced with student id
For example - 12345
And the url shoud be like following:
http://localhost:5000/api/12345

Related

Trying to work with POST request using Postman, cosmosDB and NodeJs

I am trying to learn the way API's work. Here I am trying to get the POST method to work. I am using this code to make the document in the database,
app.post('/add', async (req, res) => {
try {
const data = require('./test.json');
const newItemId = Math.floor(Math.random() * 1000 + 10).toString();
data.id = newItemId;
data.Partnership_Id = newItemId;
//for testing purpose only
let documentDefinition = {
"id": newItemId,
"name": "Angus MacGyver",
"state": "Building stuff"
};
// Open a reference to the database
const dbResponse = await cosmosClient.databases.createIfNotExists({
id: databaseId
});
let database = dbResponse.database;
const { container } = await database.containers.createIfNotExists({id: containerId});
// Add a new item to the container
console.log("** Create item **");
const createResponse = await container.items.create(data);
res.redirect('/');
} catch (error) {
console.log(error);
res.status(500).send("Error with database query: " + error.body);
}
})
Here I am using test.json for the data input. I am making a fake id using newItemId for data.id and data.Partnership_Id.
With this approach, I can make a document in the database and can check on Postman too but there is nothing in the Body tag in Postman.
I am confused on this part, I feel like the data for the new document should be passed through the Postman Body rather than me using newItemId for it.
This might be a silly question to ask but I am trying to get my head around how API works and how to pass data in them.
IDs are almost always auto generated on the backend (or at least should be) when creating a database resource, so what you have seems to be correct. I would recommend using a library like nanoid to generate the ids though, just to remove the potential for errors.
Its is RESTful convention to return created data, so in this case you would return a JSON on the created document, and then redirect etc on the front end (to ensure complete separation of backend front end - so you can say host them separately). Your approach is also fine and works though.
My advice is to think of your backend and frontend as been completely separate, I would have a project for each personally. This was it is more clear how everything links together.

Writing a Post Request in Express to make a List with given variables

I am trying to figure out how to make a list using a Post Request through Express. I'm retrieving Video Game data through an api and I'd like to use the data I get there and add specific aspects to a list.
For example:
let name = localStorage.getItem("name");
let id = localStorage.getItem("id");
let cover = localStorage.getItem("cover");
fetch("http://localhost:3000/genre?search=" + id, {})
.then((response)=>{
return response.json();
})
.then((response)=>{
let GenreHelper=[];
for(let n=0;n<=response.length;n++) {
GenreHelper[n]=response[n]["name"];
document.getElementById("genre").innerText=GenreHelper.toString();
}
});
here I am getting id, name, cover and genres of a specific game and I'd like to give the name and cover over as a variable to a new html site to make a list.
I coded a button into my html to test the Post action
<form id="form" action="/addtolist" method="POST">
<button type="submit">Submit</button>
</form>
and I used a simple Post request to see if it works.
app.post('/addtolist',(req,res)=>{
console.log("Test");
});
This does work but I have no idea how I can use the Post request to grab the variable name for example and pass it onto a new html page or into a new javascript file.
I'd comment, but don't have enough points to do that. However, post data is usually found on the req.body. From your html it does not look like you are sending any parameters though. If you are using express install body-parser
//in app.js
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
//then in your route
app.post('/addtolist',(req,res)=> {
const name = req.body.name; //req.body contains the values you send
const id = req.body.id;
});
You need to make sure you are sending values though which you are not yet doing.
You can use fetch like in your GET example and send a POST on button click.

Trying to get a snapshot of a variable from firebase gives me an error

Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})

how to fix these when using neo4j_driver in nodejs?

I am having several problems when trying to use neo4j in nodejs at the backend.
The following seems fine, but I could not see any nodes in local database browser.
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
session.run('CREATE (a:person {name: "aaaa")-[a:work_at]->(b:company {type:"Inc"})');
session.close();
driver.close();
at the local browser
http://localhost:7474/browser/
I tried to see these added nodes by
match (a) return a
but nothing came out.
So, where above nodes are now? how do I know that i added something to database?
Since above code seems fine, I put it inside a function in a module, called it in another module. The problem is that I got an error, how is this possible? It is the same code, OMG!
function test() {
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
session
.run( 'CREATE (a:person {name: "aaaa")-[a:work_at]->(b:company {type:"Inc"})' )
.then( () => {
console.log( 'add a node' );
session.close();
driver.close();
})
.catch(error =>{
console.log( error );
session.close();
driver.close();
return error;
})
}
I keep getting the following error. Searched everywhere, but could not fix it.
Error: Connection was closed by server
How can I specify where to put my database files, name of the database file and so on?
I wanted to import data to noe4j from csv file.
Can I use 'load csv' like the following
session.run('load csv from .....')
can I do that?
I saw every one just using 'load csv' from commend line.
If I must have to do from command line, how can I specify the path of the file?
Anyone point out what I am doing wrong?
Please help!
Your Cypher query has a couple of major problems, and will not work.
You omitted the } when assigning the name property to the person node.
You are attempting to use the same identifier, "a", in two conflicting ways: for a node and for a relationship.
Something like this would work (I left out all identifiers, since your current query doesn't need them):
CREATE (:person {name: "aaaa"})-[:work_at]->(:company {type:"Inc"})

Node.js connecting to a mongodb

I have been following this tutorial to try and get mongodb node.js, express, and jade to work together, but I can not for the life of me get the program to access any information from the database.
here is the code in app.js that is supposed to access the database.
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
....a few lines down....
app.use(function(req,res,next){
req.db = db;
next();
});
here is the code handling the routes:
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
And here is the code in userlist.jade: it is designed to purely figure out what the contents of userlist are. It is supposed to contain the information in the database (which has 3 entries with 2 pieces of data for each). I have other jade code from an example online that runs and is essentially just a 'Hello World' program.
doctype html
html(lang="en")
head
title= pageTitle
body
#{userlist}
the page outputs to this:
<[object Object],[object Object],[object Object]>
This explains why I was getting errors looping through the data, but what I need help with is getting the program to actually get the proper information from the database.
Extra information:
I can access the database through command prompt and view the data I put it.
I am using Windows 8.1
Update: code that makes it work!
index.js (route handler):
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
I'm not sure exactly why this is working now because I did a lot of testing to make sure I was sending the right data over which include copying and pasting code from the tutorial, but it works now!
Edit: I got closer to the solution by confirming that it is in fact pulling data from the server, just tested it and verified with the tutorial the code I should be using and it is now functioning properly. Added proper code.
I believe you are getting this output because docs in the callback is an array. Can you loop through docs and simply print individual documents to the console? This will verify that the data access part is working, and you can figure out HTML output afterwards.

Categories

Resources