I am using this code to take user input, process it into a usable format and then post it to a Node Express server. When the write function is called the data is 'undefined'?
when I open this code as a file in the browser it works fine except for the fetch post because I am using Node-fetch.
When I serve the page and hard code the data the fetch works fine too.
I am also using Browserify/watchify to bundle Node-fetch with my code and this seems to be the problem. When I moved the fetch into the the same function that processes the input it works fine.
For some reason Browserify isn't sending the data to the write function.
I'd really like to keep the server communications separate from client side data processing.
Any suggestions?
function add_cat() {
let name = document.getElementById("name").value;
const nodePros = document.querySelectorAll('input.pro');
const nodeCons = document.querySelectorAll('input.con');
let stringPros = [];
let stringCons = [];
nodePros.forEach(currentValue => {
let pro = currentValue.value.toString();
if (pro.length > 0) {
stringPros.push(pro);
}
});
nodeCons.forEach(curValue => {
let con = curValue.value.toString();
if (con.length > 0) {
stringCons.push(con);
}
});
write_cat(name, stringPros, stringCons);
}
module.exports = add_cat;
function write_cat(name, stringPros, stringCons) {
const fetch = require('node-fetch');
(async() => {
const rawResponse = await fetch('http://localhost:8080/api/categories?', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
pros: stringPros,
cons: stringCons
})
})
const content = await rawResponse.json();
console.log(content);
})();
}
module.exports = write_cat;