How to create PUT function in AngularJS with Mongoose - javascript

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.

Related

How to delete a forge bucket from Autodesk forge

I am successfully creating Bucket and uploadFile successfully using sample.
https://github.com/Autodesk-Forge/forge-extensions
I added the delete function
But when I delete the bucket I get an error.
----oss.js---
router.post('/buckets', async (req, res, next) => {
let payload = new PostBucketsPayload();
payload.bucketKey = config.credentials.client_id.toLowerCase() + '-' + req.body.bucketKey;
payload.policyKey = 'transient'; // expires in 24h
try {
// Create a bucket using [BucketsApi](https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/docs/BucketsApi.md#createBucket).
//Bucket createBucket(postBuckets, opts, oauth2client, credentials)
await new BucketsApi().createBucket(payload, {}, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
router.delete('/buckets/delete', async (req, res, next) => {
const encoded_bucketKey = encodeURI(req.bucketKeyID);
try {
// Delete a bucket using
await new BucketsApi().deleteBucket(encoded_bucketKey, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
-----------ForgeTree.js -------
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function deleteBucket() {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
switch (node.type) {
case 'bucket':
jQuery.ajax({
url: '/api/forge/oss/buckets/delete',
type:'delete',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': node.text , 'bucketKeyID' : node.id}),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
},
error: function (err) {
alert('Bucket delete error:')
console.log(err);
}
});
break;
}
console.log("Delete Bucket=%j", node)
}
I checked the config.js in the sample, it doesn't include bucket:delete scope when acquiring the token by default. Have you added the scope in your code?
Also inside delete route,
const encoded_bucketKey = encodeURI(req.bucketKeyID);
should be
const encoded_bucketKey = encodeURI(req.body.bucketKeyID);
Otherwise, you'll have undefined as encoded_bucketKey.

Use a value from a function into another function nodejs express

I want to return the value that has been declared in the first Function CreateTag and using it as variable in the second Function CreateStream, but it won't work..
I'm working with nodejs Express.
I try to use RETURN but it won't work..
I have tried it in differance ways, but still not work..
Can you someone help me, please?
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = function hi (TanentValue) {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
//console.log(res)
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
return getResult;
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
}
//Function 2: createStream
var createStream = function (TanentValue) {
var https = require('https');
var galvani = hi(); // --------> here I made a variable to call return value
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue);
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue);
res.send('Stream and Tag has been created');
});
module.exports = router;
you can not directly return value from async function. you have to use promise. something like this:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = function (TanentValue) { // function should be anonymouse
return new Promise((resolve, reject) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
//console.log(res)
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
resolve(getResult); // success call
})
})
;
req.on('error', (error) => {
reject(error); // error call
});
req.write(data);
req.end();
});
}
//Function 2: createStream
var createStream = function (TanentValue) {
createTag().then((val) => {
var https = require('https');
var galvani = val; // use that value from sucess call
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
})
})
;
req.on('error', (error) => {
console.error(error)
});
req.write(data);
req.end();
})
.catch((error) => {
// handle error from createTag function here
});
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue);
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue);
res.send('Stream and Tag has been created');
});
module.exports = router;
You can solve it using just callback function or the promise.
Using callbacks.
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = (TanentValue, callback) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
callback(false, getResult);
})
});
req.on('error', (error) => {
//console.error(error)
callback(true, error);
});
req.write(data);
req.end();
}
//Function 2: createStream
var createStream = (TanentValue, callback) => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
createTag(TanentValue, (is_error, galvani) => {
if(err || !data){
// do error handling...
callback(true); // true for there was an error
}else{
var req = https.request(options, (res) => {
res.on('data', (d) => {
callback(false);
console.log(galvani); // -----> use the variable here
})
});
req.on('error', (error) => {
callback(true);
console.error(error)
});
req.write(data);
req.end();
}
})
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
/*
// Since the stream seems to depend on the tag created,
// you don't need to call createTag explicitly because
// it is always/already called from createStream.
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue, function(is_error, data){
if(!is_error){
// do something
}else{
// do error handling
console.error(error);
res.send('Tag could not be created, please try later again..');
}
});
*/
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue, is_error => {
if(!is_error){
res.send('Stream and Tag has been created');
}else{
res.send('Stream could not be created, please try later again..');
}
});
});
module.exports = router;
Using Promise
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
//Function 1: createTag
var createTag = TanentValue => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
schemaPath: "Tag"
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/tag?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("hi tag")
var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
resolve(getResult);
})
});
req.on('error', (error) => {
//console.error(error)
reject(error);
});
req.write(data);
req.end();
})
}
//Function 2: createStream
var createStream = TanentValue => {
var https = require('https');
var data = JSON.stringify({
name: TanentValue,
});
var options = {
hostname: 'qlik_dev.be',
path: '/meteor/qrs/stream?xrfkey=1234567890123456',
method: 'POST',
headers: {
'x-qlik-xrfkey': '1234567890123456',
'hdr-usr': 'gak\\gaka',
'Content-Type': 'application/json'
},
};
createTag(TanentValue).then( galvani => {
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(galvani); // -----> use the variable here
resolve(d);
})
});
req.on('error', (error) => {
console.error(error)
reject({ msg: 'request error while creating the stream', error: error})
});
req.write(data);
req.end();
})
}).catch( error => {
// do error handling...
reject({msg: 'Error while creating a tag', error: error}); // true for there was an error
});
}
//homepage
router.get('/', function (req, res) {
res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
/*
// Since the stream seems to depend on the tag created,
// you don't need to call createTag explicitly because
// it is always/already called from createStream.
//create tag
console.log('POST / Call Create Tag');
createTag(req.body.TanentValue).then( data => {
// do something
}).catch( error => {
// do error handling
});
*/
//create stream
console.log('POST / Call Create Stream');
createStream(req.body.TanentValue).then( data => {
res.send('Stream and Tag has been created');
}).catch(error => {
// 'Stream could not be created, please try later again..'
res.send(error.msg);
});
});
module.exports = router;
Very handfull!! thank you it works!
But while passing the data (Json) from function 1 to function 2 with Promise, the data (json) is undefine in function 2. If I pass a data (String) from function 1 to function 2 than it works..
Why does it give me 'undefine' when it is a json?
//var id;
var req = https.request(options, (res) => {
//console.log(res)
res.setEncoding('utf8');
res.on('data', function (data) {
var json = JSON.parse(data);
var TagId = JSON.stringify(json[0]);
console.log("2 hi getTap");
console.log(TagId); // -------> here it works well
resolve(TagId);
});
});
var req = https.request(options, (res) => {
res.on('data', (d) => {
console.log("3 hi createStream");
console.log(galvani); // -------> here it doesn't work.. it gives me undefine
})
});
here a printscreen of response

angular promises and nodejs http get response

I would use the promises of angularJS to fill data to a grid. I'd like to load data "row by row" as soon as the nodeJS's server, on which use the module "mssql" with the "stream" enabled, back to client every single line from the DB.
On the client side I use these functions:
function asyncGreet() {
var deferred = $q.defer();
var _url = 'http://localhost:1212/test';
$http.get(_url).
then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
}, function(value) {
deferred.notify(value); //<<-- In "value" I would like to get every single row
});
return deferred.promise;
}
$scope.btnTest = function () {
var promise = asyncGreet();
promise.then(function(res) {
console.log('Success: ' + res.data + "\n");
}, function(reason) {
console.log('Failed: ' + reason);
}, function(update) {
console.log('Got notification: ' + update); //<<--
});
};
On nodeJS server those:
app.get('/test', function (req, res) {
//sql for test
var _query = 'select top 50 * from tb_test';
var sql = require('mssql');
var connection;
var config = {
user: 'testUser',
password: '12345',
server: 'localhost\\test',
database: 'testDB',
stream: true
};
connection = new sql.Connection(config, function (err) {
var request = new sql.Request(connection);
request.query(_query);
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
//res.send(columns);
});
request.on('row', function(row) {
res.write(JSON.stringify(row)); //<<-- I would like intercept this event on client side
// and get the result in my angularJS function on deferred.notify
});
request.on('error', function(err) {
// May be emitted multiple times
console.error(err)
});
request.on('done', function(returnValue) {
// Always emitted as the last one
res.end('DONE');
});
});
});
Anyone can help me with this?
Thanks!
I'm done it using socket.io :)
On angularJS side:
// count the row for test only
$scope.count = 0;
$scope.prova = function () {
mySocket.emit('getTableByRow', {});
mySocket.on('resRow', function (data) {
if (data.event == 'ROW') {
$scope.count += 1;
}else {
$scope.count += " !!DONE!! ";
}
});
};
On NodeJS side:
[ ... connection with DB ... ]
io.on('connection', function (socket) {
socket.on('getTableByRow', function (data) {
_getTableByRow(socket, data);
});
});
_getTableByRow function:
var _getTableByRow = function (socket, data) {
var _query = 'select top 50 * from tb_test';
request.query(_query);
request.on('row', function(row) {
// return only the ids for test
socket.emit('resRow', {event: 'ROW', data: row.id.toString()});
});
request.on('done', function(returnValue) {
socket.emit('resRow', {event: 'DONE'});
});
request.on('recordset', function(columns) {
console.log(columns);
});
request.on('error', function(err) {
socket.emit('resRow', {event: 'ERROR', data: err});
});
}
In this way, as soon as one row is read from the DB, it is immediately sent to the client :)

Trying to use prisimic and Node.js with express

I have partially got this starter kit from prismic working, but I am having trouble modifying it. Currently the project outputs everything, and I would like to output different collections in different lists.
I am very new to express, which is what this is using. I am not sure how to use the prismic query in this case to output a separate list for each collection or at least specified collections?
The predicate query according to the prismic api that works is this [:d = at(document.tags, ["ktblog"])]
Here is the EJS template where my list is being outputted
<ul id="list">
<% for(var i=0; i<docs.results.length; i++) { %>
<li>
<a href="<%= ctx.linkResolver(ctx, docs.results[i]) %>">
<%= docs.results[i].slug %>
</a>
</li>
<% } %>
</ul>
There is a index.js file
var prismic = require('../prismic-helpers');
// -- Display all documents
exports.index = prismic.route(function(req, res, ctx) {
ctx.api.form('everything').set("page", req.param('page') || "1").ref(ctx.ref).submit(function(err, docs) {
if (err) { prismic.onPrismicError(err, req, res); return; }
res.render('index', {
docs: docs
});
});
});
// -- Display a given document
exports.detail = prismic.route(function(req, res, ctx) {
var id = req.params['id'],
slug = req.params['slug'];
prismic.getDocument(ctx, id, slug,
function(err, doc) {
if (err) { prismic.onPrismicError(err, req, res); return; }
res.render('detail', {
doc: doc
});
},
function(doc) {
res.redirect(301, ctx.linkResolver(ctx, doc));
},
function(NOT_FOUND) {
res.send(404, 'Sorry, we cannot find that!');
}
);
});
// -- Search in documents
exports.search = prismic.route(function(req, res, ctx) {
var q = req.query['q'];
if(q) {
ctx.api.form('everything').set("page", req.param('page') || "1").ref(ctx.ref)
.query('[[:d = fulltext(document, "' + q + '")]]').submit(function(err, docs) {
if (err) { prismic.onPrismicError(err, req, res); return; }
res.render('search', {
docs: docs,
url: req.url
});
});
} else {
res.render('search', {
docs: null,
url: req.url
});
}
});
and there is a prismic helper file
var Prismic = require('prismic.io').Prismic,
Configuration = require('./prismic-configuration').Configuration,
http = require('http'),
https = require('https'),
url = require('url'),
querystring = require('querystring');
// -- Helpers
exports.getApiHome = function(accessToken, callback) {
Prismic.Api(Configuration.apiEndpoint, callback, accessToken);
};
exports.getDocument = function(ctx, id, slug, onSuccess, onNewSlug, onNotFound) {
ctx.api.forms('everything').ref(ctx.ref).query('[[:d = at(document.id, "' + id + '")]]').submit(function(err, documents) {
var results = documents.results;
var doc = results && results.length ? results[0] : undefined;
if (err) onSuccess(err);
else if(doc && (!slug || doc.slug == slug)) onSuccess(null, doc)
else if(doc && doc.slugs.indexOf(slug) > -1 && onNewSlug) onNewSlug(doc)
else if(onNotFound) onNotFound()
else onSuccess();
});
};
exports.getDocuments = function(ctx, ids, callback) {
if(ids && ids.length) {
ctx.api.forms('everything').ref(ctx.ref).query('[[:d = any(document.id, [' + ids.map(function(id) { return '"' + id + '"';}).join(',') + '])]]').submit(function(err, documents) {
callback(err, documents.results);
});
} else {
callback(null, []);
}
};
exports.getBookmark = function(ctx, bookmark, callback) {
var id = ctx.api.bookmarks[bookmark];
if(id) {
exports.getDocument(ctx, id, undefined, callback);
} else {
callback();
}
};
// -- Exposing as a helper what to do in the event of an error (please edit prismic-configuration.js to change this)
exports.onPrismicError = Configuration.onPrismicError;
// -- Route wrapper that provide a "prismic context" to the underlying function
exports.route = function(callback) {
return function(req, res) {
var accessToken = (req.session && req.session['ACCESS_TOKEN']) || Configuration.accessToken || undefined
exports.getApiHome(accessToken, function(err, Api) {
if (err) { exports.onPrismicError(err, req, res); return; }
var ref = req.query['ref'] || Api.master(),
ctx = {
api: Api,
ref: ref,
maybeRef: ref == Api.master() ? undefined : ref,
oauth: function() {
var token = accessToken;
return {
accessToken: token,
hasPrivilegedAccess: !!token
}
},
linkResolver: function(ctx, doc) {
return Configuration.linkResolver(ctx, doc);
}
};
res.locals.ctx = ctx;
callback(req, res, ctx);
});
};
};
// -- OAuth routes
var redirectUri = function(req) {
return req.protocol + '://' + req.get('Host') + '/auth_callback';
};
exports.signin = function(req, res) {
exports.getApiHome(undefined, function(err, Api) {
if (err) { exports.onPrismicError(err, req, res); return; }
var endpointSpec = url.parse(Api.data.oauthInitiate);
endpointSpec.query = endpointSpec.query || {};
endpointSpec.query['client_id'] = Configuration.clientId;
endpointSpec.query['redirect_uri'] = redirectUri(req);
endpointSpec.query['scope'] = 'master+releases';
res.redirect(301, url.format(endpointSpec));
});
};
exports.authCallback = function(req, res) {
exports.getApiHome(undefined, function(err, Api) {
if (err) { exports.onPrismicError(err, req, res); return; }
var endpointSpec = url.parse(Api.data.oauthToken),
h = endpointSpec.protocol == 'https:' ? https : http,
postData = querystring.stringify({
'grant_type' : 'authorization_code',
'code': req.query['code'],
'redirect_uri': redirectUri(req),
'client_id': Configuration.clientId,
'client_secret': Configuration.clientSecret
});
var postOptions = endpointSpec;
postOptions.method = 'POST';
postOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
};
var postRequest = h.request(postOptions, function(response) {
var jsonStr = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
jsonStr += chunk;
});
response.on('end', function () {
var accessToken = JSON.parse(jsonStr)['access_token'];
if(accessToken) {
req.session['ACCESS_TOKEN'] = accessToken;
}
res.redirect(301, '/');
});
});
postRequest.write(postData);
postRequest.end();
});
};
exports.signout = function(req, res) {
delete req.session['ACCESS_TOKEN'];
res.redirect(301, '/');
};
You can specify a collection in the "form" call, instead of 'everything'. Typically if you have a 'foobar' collection, you can restrict any query to this collection this way:
ctx.api.form('foobar')...
You will have to make one call for each collection you want to display.

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

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
});

Categories

Resources