How to make a GET and POST request to an external API? - javascript

var Attendance = require('../../../collections/attendance').Attendance;
var moment = require('moment');
module.exports = function(app) {
app.get('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.getByUser(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var job = d['attendance'];
if (typeof job != undefined) {
res.json(job);
console.log('This is it' + job['status']);
} else
res.json('No data Present', 200);
}
});
});
app.post('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.create(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var attendance = d['attendance'];
if (typeof job != undefined) {
console.log('Attendance record created' + attendance);
res.json(attendance);
} else
res.json('No data Present', 200);
}
});
});
}
This is the api code I to which I need to make the GET and POST request. But I have no idea how to do it.

It looks like your code is using express which would normally be good for building and API for your app. However to make a simple request to a third party api and staying in node.js why not try the request module which is great. https://www.npmjs.org/package/request
Your example does not show what the path of the request is or if you need any additinal headers etc but here is a simple example of a GET request using request.
var request = require('request');
function makeCall (callback) {
// here we make a call using request module
request.get(
{ uri: 'THEPATHAND ENDPOINT YOU REQUEST,
json: true,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
}
},
function (error, res, object) {
if (error) { return callback(error); }
if (res.statusCode != 200 ) {
return callback('statusCode');
}
callback(null, object);
}
);
}
or jquery .ajax from a front end client direcct to your path
$.ajax({
url: "pathtoyourdata",
type: "GET",
})
.done(function (data) {
//stuff with your data
});

Related

How to create PUT function in AngularJS with Mongoose

The GET request to the Mongo works but the PUT is not working and I suspect that the path from controller to router is bad. I've tried using update() and findByIdAndUpdate() with no luck. I'm not hitting the router and if I do, I'm not seeing the data updated in Mongo. I'm using express, node and mongoose.
retail.controller.js
myApp.controller("RetailController", [
"RetailService",
"$routeParams",
"$http",
function(RetailService, $routeParams, $http) {
var self = this;
//self.isBusy = true;
self.getMovies = function(id) {
self.getDetails(id);
self.getApiMovies(id);
};
// Get data from MongoDB Movies Table
self.getDetails = function(id) {
$http({
method: "GET",
url: "/movies/data_store/" + id
}).then(function(response) {
self.productData = response.data[0];
console.log(self.productData);
});
};
self.getApiMovies = function(id) {
$http({
method: "GET",
url: "/movies/api/" + id
}).then(function(response) {
let data = response.data.product.item;
self.apiData = data;
});
};
self.updatePrice = function(id, data) {
$http({
method: "PUT",
url: "/update/" + id,
data
}).then(function(response) {
console.log(response);
});
};
}
]);
retail.router.js
var express = require("express");
var router = express.Router();
var MyRetail = require("../models/myretail.schema");
var request = require("request");
// Data route to API
router.get("/api/:id", function(req, res) {
var apiURL = "http://redsky.target.com/v2/pdp/tcin/13860428?price";
request(apiURL, function(error, response, body) {
if (error) {
console.log("error making Redsky API request");
res.sendStatus(500);
} else {
res.send(body);
}
});
}); // End route to API
// Data route to dB with :id
router.get("/data_store/:id", function(req, res) {
MyRetail.find({ id: req.params.id }, function(databaseQueryError, data) {
if (databaseQueryError) {
console.log("database query error", databaseQueryError);
res.sendStatus(500);
} else {
res.send(data);
}
});
}); // End data route to dB with :id
router.put("/update/:id", function(req, res) {
console.log(req.body.current_price.value);
console.log(req.body._id);
MyRetail.findByIdAndUpdate(
{ id: req.body._id },
{ $set: { "current_price.$.value": req.body.current_price.value } }
),
function(databaseQueryError, data) {
console.log(data);
if (databaseQueryError) {
console.log("database query error", databaseQueryError);
res.sendStatus(500);
} else {
res.send("data updated");
}
};
});
module.exports = router;
I'm looking for some help or a push in the right direction as to how to complete the PUT
Angularjs Service :
self.updatePrice = function(id, data) {
var URL = "/update/" + id;
$http.put( URL, data).then(function (response,error) {
if (error) {
console.log('error : '+JSON.stringify(error));
} else {
console.log('response : '+JSON.stringify(response));
}
})
};
Server Side :
router.put('/update/:id', function(req, res) {
console.log(req.body.current_price.value);
console.log(req.body._id);
MyRetail.update(
{ id: req.body._id },
{ $set: { "current_price.0.value": req.body.current_price.value } }
,function(databaseQueryError, data) {
console.log(data);
if (databaseQueryError) {
console.log("database query error", databaseQueryError);
res.sendStatus(500);
res.json({message : "data not updated"});
} else {
res.json({message : "data updated"});
}
});
});
Try this!Please variable/field name
for $ operator read documentation you need have current_price in find query.

When I'm testing create script in auth0 it use get user script. Why?

When I'm trying to use create script(button try in custom DB connection or try connection) Auth0 use get user script. Examples:
enter image description here
And then Auth0 use get user script.
Here is my create script:
function create(user, callback) {
var request = require('request');
var API_ENDPOINT = configuration.ENDPOINT_LOCAL + "/api/create/account/";
user.user_metadata = user.user_metadata || {};
request.post({
url: API_ENDPOINT,
json: {
email: user.email,
password: user.password,
nickname: user.user_metadata.nickname,
employee_id: user.user_metadata.employee_id,
company_code: user.user_metadata.company_code,
email_verified: false
}
}, function (err, response, body) {
if (err) {
return callback(err);
}
if (response.statusCode != 200 && response.statusCode != 201) {
return callback(new Error('Forbidden'));
}
callback(null);
});
}
and Here is my get user script:
function getByEmail(email, callback) {
var request = require('request');
var IDP_ENDPOINT = configuration.ENDPOINT_LOCAL + "/api/account";
request.get({
url: IDP_ENDPOINT + '?email=' + email
}, function (err, response, body) {
if (err) {
return callback(err);
}
if (response.statusCode != 200) {
return callback(new Error('Forbidden'));
}
callback(null, JSON.parse(body));
});
}
I really don't know why because two days before all were working.

Node js sending multiple requests after 20 secs

My node js app is making multiple http request if there is delay in response of say 20 secs. Below is the sample code for the same.
First I make call to the getAPI function from browser. getApi function calls the getAccessToken API, after receiving the accesstoken I am calling the testApi. Now if there is a delay of 20 secs in response from testApi then getAccessToken Api is getting called again. I don't want to use promise. Can anyone point out what I am missing or doing wrong here?
shttp = require('http-https');
exports.getAPI = function(typeObj, request, response, callback) {
var userConf; //contains info such as port, host, url etc
_this.getAccessToken(function(tokenResponse) {
var tokenInfo = JSON.parse(tokenResponse);
var accessToken = JSON.parse(tokenInfo.response);
accessToken = accessToken.access_token;
if(accessToken) {
_this.testApi(userConf,accessToken,function(sjmResponse) {
callback(sjmResponse);
}
} else {
callback(JSON.stringify({"payLoad":null,"reasonCode":"fail","status":null}));
}
});
};
exports.getAccessToken = function(cb) {
var tokenConf; //contains info such as port, host, url etc
var httpReq = shttp.request(tokenConf, function(res) {
res.setEncoding('utf8');
if (res.statusCode == 200) {
var body = "";
res.on('data', function (result) {
body += result;
});
res.on('end', function (){
cb(JSON.stringify({error: '', response: (body)}));
});
} else {
cb(JSON.stringify({error: 'Failed to get user access token '+res.statusCode, response:''}));
}
});
httpReq.on('error', function(e) {
cb(JSON.stringify({error: 'Failed to get user access token'+e, response:''}));
});
httpReq.end();
};
exports.testApi = function(userConf,accessToken,sjmCallback) {
var userConf; //contains info such as port, host, url etc
var httpSubmitReq = shttp.request(userConf, function(res) {
res.setEncoding('utf8');
if (res.statusCode == 200) {
var body = "";
res.on('data', function (result) {
body += result;
});
res.on('end', function () {
sjmCallback(body);
});
} else {
sjmCallback(JSON.stringify({"payLoad":null,"reasonCode":"fail","status":null}));
}
});
httpSubmitReq.on('error', function(e) {
sjmCallback(JSON.stringify({"payLoad":null,"reasonCode":"fail","status":null}));
});
httpSubmitReq.end();
};
app.get('/testApi', function (req, res) {
var typeObj = {};
typeObj.apiType= 'testApi';
try {
getAPI(JSON.stringify(typeObj), req, res, function(response) {
res.end(response);
});
} catch(err) {
res.end(err);
}
});

Node.js: Async fs.writeFile queue is creating race condition?

I am trying to use async with node.js to handle multiple incoming POST requests to edit a JSON file. No matter how I refactor it, it will always make one of the edits and not the other. I though that using async.queue would force the operations to handle sequentially? What am I doing wrong?
My code:
var editHandler = function(task, done) {
var req = task.req;
var res = task.res;
fs.stat( "./app//public/json/" + "data.json", function(err, stat) {
if(err == null) {
console.log('File exists');
} else if(err.code == 'ENOENT') {
console.log("Error");
} else {
console.log('Some other error: ', err.code);
}
});
console.log(req.params.id);
console.log(req.body);
fs.readFile( "./app//public/json/" + "data.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data[req.params.id] = req.body.school;
//console.log( data );
fs.writeFile("./app//public/json/" + "data.json", JSON.stringify(data), function (err){
if(err) {
return console.log(err);
}
})
res.redirect('/');
});
};
//Make a queue for the services
var serviceQ = async.queue(editHandler, 20);
serviceQ.drain = function() {
console.log('all services have been processed');
}
app.post('/edit_school/:id', function(req, res) {
serviceQ.push({req: req, res: res })
})
Thanks in advance for any insights! I am really new to using node.js for anything other than npm/webpack.

Upload images to twitter API from node.js

I'm attempting to post an image onto the twitter api, v1.1
I've tried just about all the example out there, and nothing seems to be able to post it.
include Posting images to twitter in Node.js using Oauth
I'm using the oauth library mentioned there, and I also had jsOauth, which I thought I'd give a shot according to https://gist.github.com/lukaszkorecki/1038408
Nothing has worked, and at this point I'm starting to lose hope on whether I can even do this.
function postStatusWithMedia(status, file) {
var err = new Object();
if(fs.existsSync(file) === false) {
err.message = "File not found :(";
parseTwitterError(err);
} else {
var oauth = OAuth(options = {
"consumerKey": consumer_key,
"consumerSecret": consumer_secret,
"accessTokenKey": access_token,
"accessTokenSecret": access_token_secret
});
callbacks = {
onSuccess : function() {
console.log('upload worked!')
},
onFailure : function() {
console.log('upload failed!');
console.dir(arguments);
}
},
uploadData = {
'status' : status,
'media' : Base64.encode(fs.readFileSync(file))
};
oauth.post('https://api.twitter.com/1.1/statuses/update_with_media.json',uploadData, callbacks.onSuccess, callbacks.onFailure);
return false;
}
}
If it can't be done, can you please explain why?
Otherwise, anything that could lead me to the right direction would be great.
var fs = require('fs');
var request = require('request');
var FormData = require('form-data');
var utf8 = require('utf8');
// Encode in UTF-8
status = utf8.encode(status);
var form = new FormData();
form.append('status', status)
form.append('media[]', fs.createReadStream(file));
// Twitter OAuth
form.getLength(function(err, length){
if (err) {
return requestCallback(err);
}
var oauth = {
consumer_key: consumer_key,
consumer_secret: consumer_secret,
token: access_token,
token_secret: access_token_secret
};
var r = request.post({url:"https://api.twitter.com/1.1/statuses/update_with_media.json", oauth:oauth, host: "api.twitter.com", protocol: "https:"}, requestCallback);
r._form = form;
r.setHeader('content-length', length);
});
function requestCallback(err, res, body) {
if(err) {
throw err;
} else {
console.log("Tweet and Image uploaded successfully!");
}
}
I ended up using request and node-form-data to manually construct a multipart/form-data request and send it with the status request, utf8 was for encoding the status into UTF-8, not doing so caused issues with '<3' and other characters.
I have not tested these code.Its from my colleague.sure the code is working.
Perhaps this will help.
//twitter_update_with_media.js
(function() {
var fs, path, request, twitter_update_with_media;
fs = require('fs');
path = require('path');
request = require('request');
twitter_update_with_media = (function() {
function twitter_update_with_media(auth_settings) {
this.auth_settings = auth_settings;
this.api_url = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
}
twitter_update_with_media.prototype.post = function(status, imageUrl, callback) {
var form, r;
r = request.post(this.api_url, {
oauth: this.auth_settings
}, callback);
form = r.form();
form.append('status', status);
return form.append('media[]', request(imageUrl));
};
return twitter_update_with_media;
})();
module.exports = twitter_update_with_media;
}).call(this);
next file
//upload_to_twitter.js
var tuwm = new twitter_update_with_media({
consumer_key: TWITTER_OAUTH_KEY,
consumer_secret: TWITTER_OAUTH_SECRET,
token: access[0],
token_secret: access[1]
});
media_picture.picture = imageURL;
if (media_picture.picture) {
console.log('with media upload');
request.head(media_picture.picture,
function (error, response, body) {
if (!error && response.statusCode == 200) {
var image_size = response.headers['content-length'];
if (image_size > 2000000) { // 2mb max upload limit
console.log('greater than 2mb');
sendMessageWithoutImage(err, req, res, next, twit, wallpost, access);
} else {
console.log('less than 2mb');
console.log('twitter text', content);
tuwm.post(content, media_picture.picture, function(err, response) {
if (err) {
console.log('error', err);
return next(err);
}
error_parse = JSON.parse(response.body);
console.log('with media response', response.body);
if (error_parse.errors) {
console.log('have errors', error_parse);
res.json({
status: 500,
info: error_parse.errors[0].code + ' ' + error_parse.errors[0].message
});
} else {
res.json({
status: 200,
info: "OK",
id: response.id
});
}
});
}
}
});

Categories

Resources