Issue
This Content is from Stack Overflow. Question asked by Gage
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)
Solution
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.
This Question was asked in StackOverflow by Gage and Answered by Kostas Minaidis It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.