Skip to content

Instantly share code, notes, and snippets.

@vgvinay2
Last active August 16, 2017 06:42
Show Gist options
  • Save vgvinay2/58ea09bef219e9d8a6da9f345e4d8718 to your computer and use it in GitHub Desktop.
Save vgvinay2/58ea09bef219e9d8a6da9f345e4d8718 to your computer and use it in GitHub Desktop.
HANDLE GET POST PUT DELETE and Query parameters in NODE JS without ExpressJS
Write a program to handle GET and POST request
/**Get request**/
var request=require('request');
request.get('https://someplace',options,function(err,res,body){
if(res.statusCode !== 200 ) {
console.log("Success");
}
});
/**Post request**/
var request = require('request');
request.post(
'http://www.yoursite.com/formpage',
{ json: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
Write a program to handle PUT and DELETE request
/** PUT REQUEST **/
var https = require('https')
var options = {
"host": "sandbox-api.uber.com",
"path": "/v1/sandbox/requests/" + req.body.request_id,
"method": "PUT",
"headers": {
"Authorization" : "Bearer " + req.body.bearer_token,
"Content-Type" : "application/json",
}
}
callback = function(response) {
var str = ''
response.on('data', function(chunk){
str += chunk
})
response.on('end', function(){
console.log(str)
})
}
var body = JSON.stringify({
status: 'accepted'
});
https.request(options, callback).end(body);
/** DELETE REQUEST**/
var q = {
query: {
"bool": {
"must_not": [
{"ids": {"values": ['1','2','3'] } }
]
}
}
};
var payload = JSON.stringify(q);
var request = http.request({
host: 'localhost',
port: 9200,
path: 'test/col/_query',
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload)
}
});
3 Write a program to handle query string and path variable in urls
var http = require('http');
var url = require('url');
http.createServer(function(req,res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query); //{Object}
res.end("End")
});
************************OR****************************
//get query&params in express
//etc. example.com/user/000000?sex=female
app.get('/user/:id', function(req, res) {
const query = req.query;// query = {sex:"female"}
const params = req.params; //params = {id:"000000"}
});
// Write a program to handle query string and path variable in urls
app.get('/example/getdata', function(req, res) {
return res.json({
query: req.query,
path: req.url
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment