I am trying to create a web page where the user can type in a subreddit name and then the webpage returns data based on that webpage like the posts, or the name of the moderators etc..
I want to create a REST api in nodejs/express.
i have done a bit of research and i think i have to get the json data from the subreddit i want and then get the relevant data...
The part i am confused is how do i start? everything i see is got to do with python but i need to do it in nodejs.
Also wont the json keep changing format... for one subreddit it will be different to another subreddit
I feel like you should check if theres an API for Reddit. Then when the user types in a subreddit, you would issue a GET request from your express route. The GET request would get the information from the Reddit API and send it back to the front.
let express = require('express');
let app = express();
app.get('/api/subredditname', (req, res) => {
//make your api request here, returning a promise hopefully
//then send your data back
.then((data) => {
res.send(data).status(200);
})
.catch((err) => {
console.log(err);
});
};
Related
I have been struggling with the Instagram APIs and can't find a solution to fetch the follower count a user on Instagram. I too have APIs where I fetch user's media and username using Instagram basic display Graph API, but I can see nowhere how to get the follower count.
I tried the https://www.instagram.com/<username>/?__a=1 url as well but it worked on my local system but when I pushed this on server it stopped working after a while, similarly I also tried
request.get(url, function(err, response, body){
if(response.body.indexOf(("meta property=\"og:description\" content=\"")) != -1){
console.log("followers:", response.body.split("meta property=\"og:description\" content=\"")[1].split("Followers")[0])
}
});
This didn't work either on my server.
This will give you the followers count from the endpoint you have mentioned.
const axios = require('axios').default;
axios.get("https://www.instagram.com/username/?__a=1")
.then(res=>{
console.log("res="+JSON.stringify(res.data.graphql.user.edge_followed_by.count));
})
.catch(err=>{
console.log("error:\n"+err);
})
.finally(()=>
console.log("end"));
Check out this website to learn how to make request with axios
Here we make a simple get request to the server and it return an Object (res.data). We then simply access the required data.
As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.
I am making a front using Express. I have a table where each row has a link that makes a GET request, so that the back-end (done with node.js) returns a file corresponding to that row.
All links make the url GET request like "/documents/table/file".
What I intend to do is for my express server to be able to know which link of what row makes the GET request with the req field of it in order to be able to return the corresponding requested file.
The request is being handled in my express server as follows:
router.get('/documents/table/file', async (req, res) =>{
//Get which element made the get petition
});
As I said before, I intend to know what link from which row of the table performs a request using the req field.
You need to pass the information about the row/item that makes the GET request, that is a must.
Now with Express there are a couple of ways to do this: Express routing.
1. Defining route params: req.params
GET Request: /documents/table/file/345 (345 is the row identifier name or id etc)
At nodejs express end:
router.get("/documents/table/file/:id", (req, res) => {
/*request parameter with this kind of route sits in req.params*/
console.log(req.params);
const requestedId = req.params.id;
});
2. Sending as query string parameters: req.query
GET Request: /documents/table/file?id=345
At nodejs express end:
router.get("/documents/table/file/", (req, res) => {
/*request parameter with this kind of route sits in req.query*/
console.log(req.query);
const requestedId = req.query.id;
});
The short version is: you can't know this.
The way this is normally handled that if a request is needed for a specific item (or row in a table), you need to add some relevant information to the url that can identify it yourself.
So if it's a GET request for /foo/get-file, and every 'file' has some kind of unique id, you might want to change your url to /foo/get-file/123 or /foo/get-file?id=123
Do you want to access specific file using get command? If so, here's an answer - Express router - :id?.
More precisely, you write something like router.get('/documents/table/file/:id), and this :id is available in req.params object.
I'm running a small Angular application with a Node/Express backend.
In one of my Angular factories (i.e. on the client side) I make a $http request to Github to return user info. However, a Github-generated key (which is meant to be kept secret) is required to do this.
I know I can't use process.env.XYZ on the client side. I'm wondering how I could keep this api key a secret? Do I have to make the request on the back end instead? If so, how do I transfer the returned Github data to the front end?
Sorry if this seems simplistic but I am a relative novice, so any clear responses with code examples would be much appreciated. Thank you
Unfortunately you have to proxy the request on your backend to keep the key secret. (I am assuming that you need some user data that is unavailable via an unauthenticated request like https://api.github.com/users/rsp?callback=foo because otherwise you wouldn't need to use API keys in the first place - but you didn't say specifically what you need to do so it is just my guess).
What you can do is something like this: In your backend you can add a new route for your frontend just for getting the info. It can do whatever you need - using or not any secret API keys, verify the request, process the response before returning to your client etc.
Example:
var app = require('express')();
app.get('/github-user/:user', function (req, res) {
getUser(req.params.user, function (err, data) {
if (err) res.json({error: "Some error"});
else res.json(data);
});
});
function getUser(user, callback) {
// a stub function that should do something more
if (!user) callback("Error");
else callback(null, {user:user, name:"The user "+user});
}
app.listen(3000, function () {
console.log('Listening on port 3000');
});
In this example you can get the user info at:
http://localhost:3000/github-user/abc
The function getUser should make an actual request to GitHub and before you call it you can change if that is really your frontend that is making the request e.g. by cheching the "Referer" header or other things, validate the input etc.
Now, if you only need a public info then you may be able to use a public JSON-P API like this - an example using jQuery to make things simple:
var user = prompt("User name:");
var req = $.getJSON('https://api.github.com/users/'+user);
req.then(function (data) {
console.log(data);
});
See DEMO
I am trying to write a json object in my node application, integrating the Twilio API. When console logging the object all objects are returned properly but when I write it to the document only the first object is written. Why? How should I change the code to see the same written response as in my console log.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
var accountSid = 'xxx';
var authToken = 'xxx';
var client = require('twilio')(accountSid, authToken);
client.messages.list({
from: "xxx",
to: "xxx"
}, function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body); // THIS WILL DISPLAY ALL OBJECTS
res.json(message.body); // THIS WILL ONLY DISPLAY THE FIRST OBJECT
});
});
});
app.listen(1337);
I am new to Node JS and think this is easy to solve, but I still can’t find the solution.
res.json(...); sends back the response. You are doing that in the first iteration over the array, hence the client only gets the first message.
If you want to extract body from all messages and send all of them back, then do that. Create an array with the data you want and send it back. Example:
res.json(data.messages.map(function(message) {
return message.body;
}));
You can only call res.json once per request. You're calling it multiple times in a loop. The first time you call it, the browser receives the response, and you'll get a headers already sent exceptions (or something like that) for all other res.json calls.
res.json actually does a data conversion to JSON. I'd be willing to bet there is something it is not dealing with, or it's simply screwing it up. If the response from Twilio is already json, you probably don't need to do that. Try res.send, instead, which just returns whatever you got back.