Express calling an api inside of a post request - node.js

I've hit a wall here, and can't really find a clear way of achieving this. I want to create a new video to add to my database. I get all the information from the view form, but a couple of the keys have to come from an api. So here's a basic example of what I have and need. What's a good way of achieving this?
router.post("/new", function(req, res){
var videoId = req.body.videoId;
var views = req.body.views;
//call the api with the video Id here somehow, and get title key for the video object below
//"www.api.com/"+videoId"
var video = {
title: title, //title from received from the api call
views: views
}
video.create(video, function(err, video){
//etc
})
});

You can use the http module built-in node to request the information from the API, otherwise request, which is probably more convenient to use.
Your code would then look like:
var request = require('request')
router.post("/new", function(req, res){
var videoId = req.body.videoId;
var views = req.body.views;
//call the api with the video Id here somehow, and get title key for the video object below
request.get('www.api.com/' + videoId, function(err, res) {
var videoData = {
title: res.title, //title from received from the api call
views: res.views
}
video.create(videoData, function(err, video){
//etc
})
})
});

Related

Post image on twitter using puppeteer

Is it possible to post an image on twitter using nodejs and puppeteer? It find it hard because when you click on the image button on twitter it opens your archive.
It's definetely possible to post image on Twitter automatically (using Node.js). Twitter API Client for node called 'twit' suits for it. You can find the package on github or npm.
// post a tweet with media
var b64content = fs.readFileSync('/path/to/img', { encoding: 'base64' })
// first we must post the media to Twitter
T.post('media/upload', { media_data: b64content }, function (err, data, response) {
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
var mediaIdStr = data.media_id_string
var altText = "Small flowers in a planter on a sunny balcony, blossoming."
var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }
T.post('media/metadata/create', meta_params, function (err, data, response) {
if (!err) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var params = { status: 'loving life #nofilter', media_ids: [mediaIdStr] }
T.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
}
})
})
// post media via the chunked media upload API.
// You can then use POST statuses/update to post a tweet with the media attached as in the example above using `media_id_string`.
// Note: You can also do this yourself manually using T.post() calls if you want more fine-grained
// control over the streaming. Example: https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js#L20
//
var filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
console.log(data)
})

How to use JSON data from api in frontend

I followed a tutorial for making an api with express and postgres. I can get all my data in json form no problem. But I have no idea how to use the data in the frontend of a site.
These are what I have in 2 different files that are linked.
index.js:
const db = require('../queries')
router.get('/classes/:id', db.getClassById)
router.get('/classes/:id/edit', db.getClassById, (req, res) => {
res.render('dashboard/editClass')
})
queries.js:
const getClassById = (req, res) => {
const id = parseInt(req.params.id)
pool.query('SELECT * FROM classes WHERE state = 1 AND classId = $1', [id], (err, results) => {
if(err){
throw err
}
res.status(200).json(results.rows)
})
}
module.exports = {
getClassById
}
The getClassById query is called by the express middleware and automatically sends the json data to the page, which will not allow the res.render('dashboard/editClass') to work.
So how would I call this query so that I can fill in a form with the data from the query so a user can see the existing data and make any changes they want?
Thanks to Mark and Marc who commented, I realized I needed to fetch the data from my own api when rendering the front end pages. I am now using axios to get this done in node and so far it is doing exactly what I was looking for.

Nodejs - Ajax delete method in using mongodb seems to work fine (no errors) but it's not working

Good day all!
I have an ajax method that sends data to the backend and the backend does operations with the data base (Rest API I think it's called).
The problem is, even thought I have no errors on frontend or backend, the operation I'm trying to complete doesn't take place. Hope you can help, thanks in advance.
//Front-end (jQuery ajax)
$(document).on('click', '.remove-product', function () {
//Get the ID variable inside the element we press
var idEl = $(this).closest('.item-box');
var id = idEl.find('.product-id').text();
console.log(id);
$.ajax({
type:'DELETE',
url: '/dashboard/:' + id,
success: ajaxMessaging('green', 'Deleted a record')
});
});
//Backend
router.delete('/dashboard/:id', (req, res)=>{
idStr = req.params.id;
id = idStr.replace(":", ""); //Because : is sent through ajax
console.log(id);
User.deleteOne({_id : mongoose.Types.ObjectId(id)}, (err)=>{
if(err) console.log(err);
});
});
Please note that I'm trying to delete an array index, but since every element has a unique id (right?) I'm trying to delete the index by id.

Request API data into Express view

Newbie here. I'm trying to send data I received from making making an API call (when the user requests the zoopla page) into an index.ejs view. I'm trying to pass the graph_url by passing it in the res.render.
The graph_url logs correctly, so the API call is coming back, however I get the following error in my terminal:
ReferenceError: graph_url is not defined
Here is my index.js request for the page:
app.get('/zoopla', function(req, res){
request(zoopla, function(err, res, data){
var data = JSON.parse(data);
var graph_url = data.area_values_url
console.log(graph_url);
});
res.render('index', { title : "zoopla", graph : graph_url});
});
graph_url is not defined because is out of the local scope, and also you are trying to render the page before the previous async request() call complete.
try with:
app.get('/zoopla', function(req, res){
request(zoopla, function(err, res, data){
if (err) {
/* handle errors */
}
var data = JSON.parse(data);
var graph_url = data.area_values_url
console.log(graph_url);
res.render('index', { title : "zoopla", graph : graph_url});
});
});

Using request within routes node / express

I'm playing around with using nodejs as a custom front end for drupal and i'm trying to come up with a way to match the backend menu system, blocks and views with the routing in express.
example route
module.exports = {
'/work': function(req, res){
//get view json for this page
request('http://site.api/casestudies', function(err, response, body){
views_body = JSON.parse(body);
//get node id from alias
request('http://site.api/alias-to-nid' + req.url, function(err, response, body){
body = JSON.parse(body);
var reqUrl = 'http://site.api/rest/api/' + body.path;
request(reqUrl, function(err, response, body){
body = JSON.parse(body);
//get the data we need
var node_title = body.title,
node_body = body.body.und[0].safe_value,
pageclass = 'not-front section-work';
res.render('work', {title: node_title, class:pageclass, node_title:node_title, node_body:node_body, views_body:views_body});
});
});
});
}
}
So, i hit /work and grab the json for the casestudies view that should exist on that page, then i lookup the node id from the /work alias using another request and finally use the node id in yet another nested request call to grab the rest of the json for the page before finally sending it on the the template.
Now - I have a feeling that this is a terrible way to go about this. What should I be doing instead!?

Resources