【发布时间】: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