Home > Blockchain >  when i click the button the post request is being sent and also console.log is working fine in app.p
when i click the button the post request is being sent and also console.log is working fine in app.p

Time:07-11

when i click the button with class(.hw) the post request is being sent and also console.log is working fine in app.post but the res.send() does not reflect in the browser.I also tried to end response but that did not make any diffrence. ALSO this is the first time i am using stack overflow also i am absolute beginner so pls explain in simple terms.

INDEX.js :

let obj = {
    message: "hello world"
};

document.querySelector(".hw").addEventListener("click",()=>{
    fetch("/",{
        method: "POST",
        headers: {
            'Content-Type':'application/json',
        },
        body: JSON.stringify(obj),
    }).then(data => {
        console.log(data);
    }).catch(err => console.log(err));
});

APP.js

const exp = require("express");
const app = exp();


app.get("/",(req,res)=>{
    res.sendFile(__dirname "/index.html");
    req.on("close",() => res.end());
});

app.get("/index.js",(req,res)=>{
    res.sendFile(__dirname "/index.js");
});

app.post("/",(req,res) => {
    req.on('data',data => {
        console.log(JSON.parse(data).message);
        res.send(JSON.parse(data).message);
    });
});

app.listen(3000,()=>{
    console.log("server started at 3000");
});

CodePudding user response:

Try this

fetch("/",{
            method: "POST",
            headers: {
                'Content-Type':'application/json',
            },
            body: JSON.stringify(obj),
        }).then(data => {
            return data.json();
        })
        .then(resData=>{console.log(resData)})
        .catch(err => console.log(err));

CodePudding user response:

See https://stackoverflow.com/a/72076993/16462950

As an alternative to parsing the JSON yourself, you can write

app.post("/", express.json(), (req,res) => {
  console.log(req.body.message);
  res.send(req.body.message);
});
  • Related