Home > Software engineering >  Send array from a javascript file to index.js in Express
Send array from a javascript file to index.js in Express

Time:09-19

I've been having trouble sending an array (or JSON object would work too) from script.js (code for my html) to index.js (my express server file).

I've researched it and it either has to do with sending the variable to an HTML file and then to another javascript file off of it (which can't be applied to this) or using localStorage (which also cannot be used inside of node) and also I've tried making a POST request and sending it that way but I couldn't figure out how to do it (making the contents of the request itself).

Please help! (sorry if I'm making a dumb question but I'm pretty inexperienced)

Code (index.js):


var express = require('express');
var path = require('path');
var app = module.exports = express();
var engines = require('consolidate');
var fs = require('fs');
app.engine('php', engines.mustache);
app.set('view engine', 'php');
app.set('views', path.join(__dirname, '/views/'));
app.use(express.static(path.join(__dirname, './public')));
app.get('/', function(req, res){
  res.render('index.php');
});

if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}
function submitColors(e) {
    fs.writeFile("./colors.txt", JSON.encode(e), (err) => {
        if(err){
            console.log(err);
        }
        else{
            console.log("Successfully sent JSON to colors.txt (Array: "   e   " and JSON "   JSON.encode(e));
        }
    });
}
app.get('/colors', function(req, res) {
  submitColors(cArray);
  res.render('index.php');
  res.send('Colors maybe sent successfully?');
});

Code (frontend index.php (no php code, i just tried php and havent turned it back):

<div id="buttons-div">
        <button id="yellow-button" onclick="changeColor('yellow')"></button>
        <button id="red-button" onclick="changeColor('red')"></button>
        <button id="blue-button" onclick="changeColor('blue')"></button>
        <button id="white-button" onclick="changeColor('white')"></button>
        <button id="green-button" onclick="changeColor('green')"></button>
        <form method="POST" action="colors">    
            <input id="submit" type="submit"></input>
        </form>
    </div>

Code (script.js):

function changeColor(e) {
    if(e == "red") {
        console.log('red');
        addColor('red');
    }
    else if (e == "blue") {
        console.log('blue');
        addColor('blue');
    }
    else if (e == "green") {
        console.log('green');
        addColor('green');
    }
    else if (e == "yellow") {
        console.log('yellow');
        addColor('yellow');
    }
    else if (e == "white") {
        console.log('white');
        addColor('white');
    }
}
function isInArray(array, string) {
    if(array.indexOf(string.toString()) >= 0) {
        console.log(array.indexOf(string.toString())   " true and is inside");
        return true;
    }
    else if (array.indexOf(string.toString()) < 0){
        console.log(array.indexOf(string.toString())   " false and is not inside");
        return false;
    }
}

var cArray = [];
function addColor(c) {
    if(isInArray(cArray, c) == true) {
        var a = cArray.indexOf(c.toString());
        delete cArray[a];
        console.log('deleted '   c   ' from the list');
        return true;
    }
    else {
        cArray.push(c.toString());
        console.log('added color '   c   ' to the list');
    }
    
}

I need to transfer my array (cArray) from the script file for coding the HTML page to the express index.js.

CodePudding user response:

Here's a very basic setup to send an Array from the client (index.html) to an Express server (server.js) in the form of JSON.

index.html:

<html>
    <body>
        <!-- We will use a simple form to submit the Array, but any JS function can do the fetch() request autonomously -->
        <form>
            <button>Submit</button>
        </form>
        <script>
        // The Array that will be send to the server:
        const arrayDestinedForServer = [ "A", 42, false ]; // This would be your cArray

        const form = document.querySelector("form");

        // Handle the form's submit event (when the button Submit gets clicked)
        form.addEventListener("submit", e =>{
            // Prevent the default HTML form submission behavior:
            e.preventDefault();

            // Send the Array as a stringified JSON to the server via an Ajax request using the Fetch API:
            fetch("http://localhost:3000/colors", {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                    },
                body: JSON.stringify(arrayDestinedForServer)
            })
            .then( res => res.json() ) // <= Handle JSON response from server
            .then( data => console.log(data) )
            .catch( error => console.error(error) );
        })
        </script>
    </body>
</html>

server.js:

const express = require("express");
const app = express();
app.use( require("express").json() ); // <== Make sure we can handle JSON data from the client

// Handle POST request from client:
app.post("/colors", (req,res)=>{
    console.log( req.body ); // <== Receives: [ 'A', 42, false ]
    res.status(200).json({ received: req.body }); // Send back a confirmation JSON response
});

app.listen( 3000, ()=>{
    console.log("Server listening on http://localhost:3000");
});

Let me know if this helps.

  • Related