Accessing JSON from Node/Express Route? - javascript

I was wondering, since Node is written in JavaScript, and I'm using ES6 to write a little fun app, is there a way to access the object I send to the route without using ajax to get it from the server/api? In other words, can I say something like
import { jsonData } from '../api/server.js';
and then be able to use jsonData as a variable in my client side controller?
In other words... I would have something like this:
var DataController = (req, res) => {
let data_client = new DataClient();
data_client.getData().then(
(data) => {
res.render('index', { jsonData: jsonData });
},
(error) => {
res.send('An error occurred. Please check your connection settings.');
}
);
Is what I'm asking possible?
If not, would I just use an XHR request or fetch?
Just wondering what my options are since I want to use Node (4.x) to its full potential. Sorry if this question was confusing or vague.

I don't think that server side file will be accessible over client side.
If you make your server side file available on client and your server.js file is generic enough to run on client side as well along with correct client side export statement , then yes you can import the jsondata with syntax like
import { jsonData } from '../api/server.js';
and use it else where
Beware that there are limited browsers that support import statement
You can check the list from here

Related

Problem with React making Get request to Node(express)

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.

How to use $get request in AngularJS after node fetches the data?

I'm building a web app that is going to use an API to display cards when you hover over card text on the app.
I'm using unirest to make the call to the API on my node express server as follows -
unirest.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards")
.header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
The data returns correctly and is displayed in my git bash console as JSON.
How do I use the Angular $get service to make a call against what node has just pulled? I guess my question is , where is this data pulled to once node gets a handle on it?
From what I understand, I would parse this information, but do I have to send this data to use it in my Angular.js file?
I hope I wrote enough information for an answer.
Thank you
If you want to pass the data to your UI, you need to make it accessible through an endpoint, so you could do something like this in your server (I'm using express for simplicity):
app.get('/my-data-endpoint', (req, res) => {
unirest.get("https://omgvamp-hearthstone-v1.p.mashape.com/cards")
.header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.end((result) => {
console.log(result.status, result.headers, result.body);
res.send(result);
});
});
and in your angular controller you can do:
$http.get('/my-data-endpoint')
.then((response) => {
console.log(response);
});
just remember to inject the $http dependency in your controller and you should be able to see the response.

Hide an API key (in an environment variable perhaps?) when using Angular

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

Meteor - transfer data from API to Server to Client

I am struggling a bit with Meteor, i have this app that i would like to connect with an API client, which provides me a Secret API key, which i must not publish (in the client).
The thing is when i send the request, i get a JSON data, and i would like to pass this data to the client.
API > Server Call -> Client (Rendering).
But so far i have not come to a solution how can i do this.
I have a basic understanding how Meteor Works, but i have a good knowledge about JavaScript/NodeJS etc.
A little bit of help would really be appreciated.
Thank you.
This sounds like a good use case for a client making a call to a server-side method. The server can then use the secret key to make an HTTP request and send the result back to the client without exposing the key. Please note that your server-method must exist inside of a server directory to avoid inadvertently shipping the key to the client (see Structuring your application).
client
Meteor.call('getApiResult', function(err, result) {
if (result) {
return console.log(result);
}
});
server
Meteor.methods({
getApiResult: function() {
var secret = 'abc123';
try {
var result = HTTP.get('http://example.com/', {params: {key: secret}});
return result.data;
} catch (_error) {
return false;
}
}
});

Passing Function from Server to Client

for a recent project of mine I need to pass two functions from my server (written in node.js) to a client javascript tag. Actually to be completly correct, the client side javascript calls an XML request and I want to return some data and two functions for him which he should be able to use.
Second thing is I want to store a javascript function into a database in the server and then fetch it if the client requests it.
Anyone knows how this can be archieved and has some experience with it?
Note: you should really consider doing this in an HTTPS connection.
OK, so you want to receive code from the server and run it on the client. You could inject a script tag to the body and let the browser execute it. However, since you trust the code. I would simply use an eval call since that's what you'll doing anyway.
Here's how it would look in an Express app:
// server
function hello() {
alert('hello');
}
app.get('/get/js/code', function (req, res) {
res.send({
code: hello.toString(),
start: 'hello()'
});
});
// client (with jQuery)
$(function () {
$.getJSON('/get/js/code', function (json) {
eval(json.code + ';' + json.start + ';');
});
});

Categories