如何从node.js中的发布请求发送响应?

时间:2020-05-13 11:47:46

标签: node.js express body-parser

我正在尝试发送来自发帖请求的回复,并且已经在互联网上看到我必须使用res.end,但在我的情况下似乎不起作用。我过去已经成功完成了发帖请求,但是现在我需要在不加载网站的情况下完成发帖请求,因此对于每个发帖请求,它都必须是异步的。

这就是我所拥有的:

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);

每次输入用户名时,我的网络浏览器控制台上都应显示“ hello”,但不会。

我在做什么错了?

0 个答案:

没有答案