How to send information from a Javascript site to the NODE.js server

Asked

Viewed 544 times

0

Guys, I have a javascript site where I get information from a Rest API (json)

i would like to delete this information to my server (A Node.js that I created that connects to the database)

is my first time working with web development , I would like to know how I make the connection between the two?

My front end

<!DOCTYPE html>
<html>

    <head>
        <style>     
            .bodyFrame {
                margin: 40px;
            }

            .headerLabel {
                font-weight: bold;
            }

        </style>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>

    <body>
        <div class="bodyFrame">
            <h2 style="text-align:center;">WIDS JSON Retrieval Example</h2>

            <button type="button" onclick="makeServiceCall()">Retrieve JSON Data</button>
            <br /><br />

            <label class="headerLabel">Programs</label>
            <ul id="programUL"></ul>
        <div>

        <script>

            function makeServiceCall() {                    
                var url = "http://widsservicedev.yaharasoftware.com/WidsService/JSON/GetPortagePrograms/?apikey=104043F0-9C24-4957-879D-046868973CC4&callback";

                $.getJSON(url, function (data) {
                    //var myArray = [];
                    //myArray[0] = data;
                    parseProgramData(data, url);
                });                 
            }

            function parseProgramData(jsonData, url) {      

                $("#dataHeader").empty();
                $("#dataHeader").append('<b>' + url + '</b>');

                var programUL = document.getElementById("programUL");       

                for (var pgmIndex = 0; pgmIndex < jsonData.Programs.length; pgmIndex++) {                   
                    var pgmLi = document.createElement("li");
                    var program = jsonData.Programs[pgmIndex];
                    var programInfoRevision = program.ProgramInfoRevisions[0];
                    var numberTitle = programInfoRevision.ProgramNumber + " " + programInfoRevision.ProgramTitle;
                    pgmLi.appendChild(document.createTextNode(numberTitle));
                    programUL.appendChild(pgmLi);                   

                    var linebreak = document.createElement("br");
                    pgmLi.appendChild(linebreak);

                    var poLabel = document.createElement("label");
                    poLabel.appendChild(document.createTextNode("Program Outcomes"));
                    poLabel.classList.add("headerLabel");                   
                    pgmLi.appendChild(poLabel);                 

                    var pgmOutcomeUL = document.createElement("UL");
                    pgmLi.appendChild(pgmOutcomeUL);

                    for (var poIndex = 0; poIndex < program.ProgramOutcomes.length; poIndex++) {                    
                        var poLi = document.createElement("li");
                        poLi.appendChild(document.createTextNode(program.ProgramOutcomes[poIndex].Description));
                        pgmOutcomeUL.appendChild(poLi);
                    }                   
                }

            }
        </script>


    </body>

    <footer>        
    </footer>
</html>

My Ode.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
/*    var config = {
        user: 'papercut',
        password: 'Portage.2018',
        server: 'devsqlcl2:1433', 
        database: 'AgrM6',
        port: "1433",
        dialect:",ssql",
        dialectOptiond:"SQLEXPRESS"
    };*/

    // connect to your database
    sql.connect('mssql://xxx:xxxx@xxxx:1433/xxx', function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query('select * from dbo.balance_papercut', function (err, recordset) {

            if (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

Thank you.

  • Tip: Do not post given of true connections in questions, always use fakes.

1 answer

1

the verb get only recovers data from the server, you want to send data in the opposite direction, you must send via POST.

On the Node you will need the following:

Install the body-parser via npm then add the following setting to your server.js before the app.get(...:

var bodyParser = require('body-parser');
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 

now replace the.get app with

app.post('/', function(req, res) {
    var body = req.body;


});

in the body variable vc will have the json sent from the client

now in the client part you need to send via Ajax POST as in the example below:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
  • A question, that body, gets everything my client sends? else url: url, date: date, Success: Success, dataType: dataType here, the date, would be the information I want to send? the url is the address of the client?

  • If the body has all the data sent to the server, this data will be in json format. There are other formats... this you will inform by the datatype parameter. It goes from json which is the best for your scenario.

  • data is the json itself and datatype if I’m not mistaken now it’s the MIME type of json "application/json"

  • Would it look like this? $. ajax({ type: "POST", url: (localhost/500 [or the server address? ], date: [VARIABLE WITH THE INFORMATION I WANT], Success: Success, dataType: MIME });

  • dataType: "application/json", the Url is the one of the server that if running local will be localhost even...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.