Okay, so when I send a POST request to /getenv, I am supposed to get the value of an env variable. The POST request works fine and there are no logs in either places (Glitch Logs and Chrome DevTools), but the problem is that the POST request returns undefined. I tried console.loging and I got the variable values correctly. Here’s how my code looks:
server.js:
var to = process.env.TO;
var from = process.env.FROM;
var title = process.env.TITLE;
var message = process.env.MESSAGE;
app.post('/getenv', function(request, response) {
var req = request.body.name;
console.log(req);
if (request.body && request.body.name) {
const getto = to;
response.send({ name: getto });
console.log(getto)
} else {
response.json({ error: "no body included" });
}
//console.log(response);
});
client.js:
var some = "Dear, ";
const data = { name: some };
console.log("Fetching...");
fetch("/getenv", {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" }
})
.then(response => console.log( response))
.then(data => {
// get the response from the server POST request
console.log(JSON.stringify(data));
// var dataa = JSON.stringify(data)
// console.log(dataa.name);
document.getElementById("to").innerText = data;
});
In case you’re wondering, I have already installed body-parser! But someone please help!!!
Weird! I just spun up a small demo in Glitch and got the same as you did … different to running on my local machine.
For anyone watching this, request.body should look like {"name":"something"}, @khalby786 is correct with request.body.name. I think my little test wasn’t refreshing lol
I created some confusion by assuming help was wanted with the server side body params. After a bit of messaging each other, I realised that the issue was with the client side fetch results.
Here is the fix for the fetch response in client.js