const http = require('http');
const fs = require('fs');
const { log } = require('console');
const server = http.createServer((req, res) => {
log(req.url )
if (req.url === '/api/data' && req.method === 'POST') {
res.writeHead(200, {
'Content-Type': 'application/json'
});
const responseData = {
message: 'This is a sample response from the API server'
};
res.end(JSON.stringify(responseData));
} else if (req.url === '/' && req.method === 'GET') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Internal Server Error');
} else {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(data);
}
});
} else {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.end('Not Found');
}
});
server.listen(3001, () => {
console.log('Server running at http://localhost:3001');
})
···
nodejs 搭建服务后
index 内容如下
<script src="https://unpkg.com/htmx.org@2.0.1"></script>
<button hx-post="/api/data" hx-swap="outerHTML">
Click Me
</button>
浏览器打开后
http:
点击按钮 可以得到 json 响应并显示
这里的路径不能是站点外的接口, 而且需要服务器渲染