【问题标题】:Respond to client after receiving client to server POST request (Node.JS)收到客户端到服务器的 POST 请求后响应客户端(Node.JS)
【发布时间】:2021-08-04 16:06:44
【问题描述】:

我一直在尝试使用 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}`);

【问题讨论】:

  • 您还没有为/ 定义POST 路由。您的服务器不知道如何响应 POST,因为您甚至没有告诉它去寻找它。

标签: javascript html jquery node.js


【解决方案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}`);

【讨论】:

    【解决方案2】:

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

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

    我看到你正在使用 ExpressJS。 here 是写路由的文档。

    【讨论】:

    • 感谢您的解释!我想我实际上理解了 Node 的一小部分!
    猜你喜欢
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多