DEV Community

loading...

Node.js send JSON to local client

binarydigit profile image Liz Rodriguez ・1 min read

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!

Discussion

pic
Editor guide
Collapse
rhymes profile image
rhymes

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 your success.

How do you send it to the client? You can use expressjs.com/en/4x/api.html#res.json

So the flow is:

  • client jQuery calls the node server
  • the node server calls the API and waits for the response
  • the response from the API is sent as a JSON response to jQuery
Collapse
binarydigit profile image
Liz Rodriguez Author

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!!

Collapse
rhymes profile image
rhymes

no worries, glad it worked!

Collapse
binarydigit profile image
Liz Rodriguez Author

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!

Collapse
jazzyclimber profile image
jazzyclimber

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!

Collapse
arikardnoir profile image
Aristoteles Lopes

i have the same doubt, you can show how it is?
How can I send in my views?

Collapse
binarydigit profile image
Liz Rodriguez Author

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:

$(document).ready(function() {
  let url = 'http://localhost:3000/';
  $('button').on('click',function(e){
      e.preventDefault();
      let data = {
          endPoint: url
          }; 
          $.ajax({
            url: url,
            method: 'POST',
            data: data,
            dataType: 'json' 
          }).done(function(response) {
              console.log(response);
          });
  }); 
});

Ultimately you can trigger it with anything, but I made a button so I understood each step of the way :) Hope this helps!

Collapse
arikardnoir profile image
Collapse
amirhatami profile image
Amirhatami

May I know what you wrote in your post function?