3
votes

I am trying to send response from post requests and on internet I have seen I have to use res.end but it does not seem to work in my case. I have done post requests in the past succesfully but now I need to do them without loading the website, so it has to be asynchronous for each post request.

This is what I have:

Game.js:

textModalContent1.addEventListener("click", () => {
  //Ask for username
  let username = prompt("Enter your new username");
  $.post("/addUser",{username: username}, function(data){ //I use jQuery for post requests
    console.log(data);
  });               
});

index.js:

const express = require('express');
const app = express();
app.use('/assets', express.static('./assets/'));

var bodyParser = require('body-parser')
app.use( bodyParser.json() ); 
app.use(bodyParser.urlencoded({     
  extended: true
})); 

app.get('/', function (req, res) {
    res.render('./index.ejs', {});
});

app.post('/addUser', function(req, res) {
    //console.log(req.body.username)
    res.end("hello"); //this should send "hello" to the client
});

app.listen(process.env.PORT || 14532);

Each time I enter a username, should appear "hello" on my web browser console but it does not.

What am I doing wrong?

Did you test with Postman or with some other tool that your endpoint /addUser is working? - Azeem
code works fine for me. eveytime you enter a username you get a response. anything else we need to know about? maybe some logs? - Mücahid Erenler
You are right. I have just tried it with Postman and it works. Weird, then the problem seems to be in my javascript code... I am assuming it is probably because prompt runs in a loop (I need to fix that), so it asks for a username multiple times. I thought it would not affect it. I am sorry. - user10021033
Ok, now it prints "hello" in the console. Apparently it was due to the loop which I have just fixed it. Should I close my question or should I keep it? - user10021033