GET POST requests in node js - node.js

Hi friends I'm new in MERN application build I want to know that How we can handle requests in nodeJs and connect mongoose to the database. Please help me out.

I would recommend the library Express.js, but you could also use another one if you want to.
Here's an example for how this could look like in Express:
const express = require('express');
const app = express();
app.use(express.json()); // necessary for req.body
app.post('login', function(req, res){
let data = req.body;
// do something..
res.sendStatus(200);
});

Related

How to consume JSON in Express JS?

In very new to express js. I just wrote a simple program to send JSON request through postman and get the response.
Why I can't get any response? it always says could not get any response. I go through several tutorials and could not figure out what exact missing here?. Here is my code.
const express = require('express');
const app = express();
app.use(express.json);
app.post('/', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(3000, () =>{
console.log("Listen in port 30000");
});
I figure out what went wrong. Here
app.use(express.json);
Should be This,
app.use(express.json());
You have to parse your json data inorder to consume it.
check the following code.
install this package.
npm i body-parser
and use it with your express object as below
let bodyParser = require('body-parser')
app.use(bodyParser.json())

ExpressJS Middleware Method to make variable available in other (module) files

I am playing around with making a NodeJS app that combines REST API functionality with MongoDB CRUD persistence. I'm pretty new to NodeJS.
Right now I've managed to connect to the Database and figured out that the rest of my code belongs inside the callback - ie only process REST request after the DB is up and available.
The challenge I'm running into in this case is understanding how to "attach" the 'client' (from mongodb.connect) to the 'request'. I need to somehow make it available in other files because I want to keep my routes separate as a best practice.
The same question applies to any variables in the main server.js file which I need to be able to access in my modules.
Here is the relevant code:
//server.js
const express = require('express')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const routes = require('./routes')
const url = 'mongodb://localhost:27017/testDB'
let app = express();
app.use(logger('dev'))
app.use(bodyParser.json())
mongodb.connect(url, {useNewUrlParser:true},(error, dbClient) => {
if (error) {
console.log(`Error: ${error}`)
process.exit(1)
}
//connected
console.log(`Connected to mongoDB`)
//what do I do here to make sure my routes can access dbClient?
app.get('/accounts', routes.getAccounts(req, res) )
app.listen(3000)
})
//./routes/index.js
const bodyParser = require('body-parser')
const errorhandler = require('errorhandler')
const mongodb = require('mongodb')
const logger = require('morgan')
module.exports = {
getAccounts: (req, res) => {
console.log("in getAccounts")
//how can I use dbClient in here?
}
}
Thank you in advance for your help!
My apologies if anything about my post isn't according to the normal standards, I'm brand new here! All critique appreciated, coding and otherwise!

Mock up SharePoint Rest API using NodeJS and ExpressJS

I'm trying to create a development environment for a small sharepoint application. The application queries a couple of Sharepoint 2013 lists and builds a custom view of the data. Rather than publishing to sharepoint every time I make a change I would like to use NodeJS and Express 4 to mock up the api. I don't need to mock up any of other CRUD activities; just the GET requests.
I started out using the following:
const express = require('express')
const fs = require('fs');
const path = require('path');
const csv = require('csvtojson');
const app = express();
function openAndSend(file, res){
csv().fromFile(path.join(__dirname,file))
.then(jsonarray)=>{
res.setHeader('Content-Type','application/json');
res.send({d:{results:jsonarray}});
});
}
app.get('/dataset',(req,res)=>{
openAndSend('./data/dataset.csv', res);
});
app.get('/people',(req,res)=>{
openAndSet('./data/people.csv', res);
});
How can I use express js to mock up something like
/api/lists/getbytitle("Data Set")/items and /api/lists/getbytitle("People")/items
I tried changing the app.get functions to app.get('/api/lists/getbytitle("Data%20Set")/items', ....); which did not work. However removing get getbytitle("...")" routed correctly.
I was able to solve the issue using express Router and a regex expression for the path/route. The most challenging part was discovering that special characters needed to be encoded.
var router = express.Router();
router.get(/getbytitle\((%22|')Data%20Set(%22|')\)\/items\/?$/i,(req,res,next)=>{
openAndSend('./data/dataset.csv', res);
});
router.get(/getbytitle\((%22|')people(%22|')\)\/items\/?$/i,(req,res,next)=>{
openAndSend('./data/people.csv', res);
});
app.use('/_api/lists',router);

app.post() method is not working in nodejs

I am new to MEAN Stack and have been developing some applications on Mean stack.But I am stuck with my app.post() method .The browser's console gives a 405 error saying that the method is not allowed.Please help me.
Here;s my code for server file in javascript
var app =express();
var mongoose =require('mongoose');
var bodyParser =require('body-parser');
var urlencodedparser=app.use(bodyParser.urlencoded({extended:false}));
var jsonParser = bodyParser.json()
app.get('/',function(request,response){
response.sendFile(__dirname+'/clients/views/index.html');
});
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
var port=process.env.PORT || 3000;
app.listen(port,function(){
console.log('Listening to the server at port '+port);
});
Based on the Application.post() Express documentation, I think you probably want to change the first line of your post listener from:
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
To this:
app.post('/api/meetups',function(req,res){
console.log(req.body);
});
I don't think it takes the additional parameter you specified related to JSON parsing. If you need to parse JSON you may want to look into using body-parser with middleware like this (which you would put ABOVE the post listener):
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Good luck!

NodeJs + Unable to access localStorage inside routes.js

In my NODEjs ( using Express ) application, I want to use Country Code inside routes.js but I am unable to access localstorage inside the routes.js
Please provide some solution.
LocalStorage is only available in browsers on the Window object.
The Window object is not available server side.
MDN
Following your comment, you could implement a route in your express application which takes the IP as part of the body.
For this to work you will need body-parser middleware. Example application:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server;
app.use(bodyParser.json());
app.get('/api/ip', function (req, res) {
res.send(req.body.ip);
});
server = app.listen(3000);
This would return the posted IP.

Resources