收到客户端到服务器的 POST 请求后响应客户端(Node.JS)

时间:2021-05-14 13:20:30

标签: javascript html jquery node.js

我一直在尝试使用 Node.JS 响应客户端请求。我发现了 Node JS - call function on server from client javascript,它似乎解释了我想要什么,只是我似乎无法将它翻译成我的程序。 这是通过 index.html 中的 POST 请求:

$.post("/", {data: 'hi'}, function(result){
      $("body").html(result);
    });

我希望它会从我的 server.js(节点)中写入调用结果:

const express = require('express');
const path = require('path');
const http = require('http');
const fs = require('fs');

function handler(data, app){
    if(req.method == "POST"){ 
        app.setHeader('Content-Type', 'text/html');
        app.writeHead(200);
        app.end(data);
    }
}

const BUILDPATH = path.join(__dirname);

const { PORT = 3000 } = process.env;

const app = express();
app.set('port', PORT);

app.use(express.static(BUILDPATH));
app.get('/*', (req, res) => res.sendFile('static/index.html', { root: BUILDPATH }));

const httpServer = http.createServer(app);

httpServer.listen(PORT);

console.info(`? Client Running on: http://localhost:${PORT}`);

2 个答案:

答案 0 :(得分:-1)

问题是,您的 Node 服务器监听的唯一路由是您使用 /* 定义的路由。如您所见,该路由将您的 index.html 文件返回给客户端。您没有指定侦听来自客户端的请求的路由。

要解决此问题,您必须定义一个路由,该路由侦听您尝试从客户端发出的请求的特定路由。

我看到您正在使用 ExpressJS。 here 是关于编写路由的文档。

答案 1 :(得分:-1)

试试这个代码:

const express = require('express');
const path = require('path');
const http = require('http');
const fs = require('fs');

function handler(data, app){
    if(req.method == "POST"){ 
        app.setHeader('Content-Type', 'text/html');
        app.writeHead(200);
        app.end(data);
    }
}

const BUILDPATH = path.join(__dirname);

const { PORT = 3000 } = process.env;

const app = express();
app.set('port', PORT);

app.use(express.static(BUILDPATH)); 
app.get('/', (req, res) => {
    res
       // best practice is to always return an status code
       .status(200)
       // just return an json object
       .json({"msg": "ok, it all works just fine"})
});

const httpServer = http.createServer(app);

httpServer.listen(PORT);

console.info(`? Client Running on: http://localhost:${PORT}`);