How to send response from a post request in node.js?

Viewed 1374

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?

0 Answers
Related