Hey everyone! Here's my setup and question:
I've created a Node.js/express server to authenticate to a API. The API we are using needs Basic Authorization over HTTPS as base64 encoded. I've accomplished this by using the npm "request" module. I authenticate and do get the JSON I expect in the body of the request response (hooray!).
The problem I'm having is, how do I send the JSON I've received to my local server's client? I'd like to grab this JSON, send to my local client with an ajax call, and append it to my DOM to eventually create a dashboard and do fun stuff.
Here's some of the server.js code:
let request = require('request');
let username = 'username@email.com';
let password = 'password@123';
let options = {
url: 'https://apiblah.com',
auth: {
user: username,
password: password
}
};
request(options, function (err, res, body) {
if (err) {
console.log(err)
return
}
let jsonData = JSON.parse(body);
console.log(jsonData); <strong>//In my console, I do see the json I want to see, hooray!
But how do I get jsonData to send to client outside of request?</strong>
});
//
app.post('/', function(req, res){
<strong>//I send request results to client side? unsure here</strong>
});
app.get('/', function(req, res){ //render index.html
res.render('index');
});
My client.js:
$.ajax({
url: "http://localhost:3000/", // the local Node server
method: 'GET',
success: function(data){
console.log(data); //display data in cosole to see if I receive it
}
Thanks alot!
Top comments (8)
Hi Liz, you have a jQuery client that calls the server through AJAX, so you decide a route, let's say
GET /dataFromApiServer
and in that function you issue the request to such API server, parse the JSON data and then "send it to the client" as a JSON response, so that jQuery can log it in yoursuccess
.How do you send it to the client? You can use expressjs.com/en/4x/api.html#res.json
So the flow is:
Annnnnd I have success! I realized I needed to do exactly what rhymes said and re-do my routing. I started my request on the client, then did the api call on the node server, and it responded. (I ended up using res.send(body) in my request function.)
Thanks for your help!!
no worries, glad it worked!
Thanks for your reply! So it's a workflow issue, I think I understand now... I'll give this a try and update with my progress!
This post is old news now but very helpful! Especially for something actually so simple. Perhaps the first time setting it up on your own it just is a little challenging to wrap your head around. Thanks Liz and rhymes!
i have the same doubt, you can show how it is?
How can I send in my views?
Hi Arristoteles,
What I ended up doing was creating a button on my client via HTML and JS client, which triggered the local node server, that then calls the API. Here is my client:
Ultimately you can trigger it with anything, but I made a button so I understood each step of the way :) Hope this helps!
Thanks Liz..
May I know what you wrote in your post function?