[英]How to properly send and receive "POST" requests to and from a server
我正在尝试为网站制作服务器。 服务器完美运行,可以正常收发数据。 我已经托管了服务器,并在 Replit 上制作了一个演示客户端 repl 来测试流程。 但不知何故,要么回复没有正确接收或发送,要么服务器不工作。 (对于客户端代码,我使用的是 JQuery)
// Client Side Code
const url = "My url";
const data = {
"file": "lol.html"
}
function start() {
console.log("test 1")
$.post(url, data, function(data, status) {
console.log(data + "is data & status is " + status);
});
}
// Server-side code
var http = require('http'); // Import Node.js core module
var fs = require('fs'); // File System
var url = require('url');
var server = http.createServer(function(req, res) { //create web server
if (req.url == '/') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "This is the Backend server for my website" }));
res.end();
}
else if (req.url == "/ping") {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Pong!" }));
res.end();
}
else if (req.url.startsWith("/read")) {
var q = url.parse(req.url, true);
var qdata = q.query;
fs.readFile(String(qdata.file), function(err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}
else if (req.url.startsWith("/get")) {
var q = url.parse(req.url, true);
var qdata = q.query;
fs.readFile(String(qdata.file), function(err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}
else {
res.end('Invalid Request!');
}
});
server.listen(5000); //6 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
有人可以告诉我如何正确执行此操作吗?
使用 axios 代替旧的数据获取技术。 它是基于 promise 的 HTTP 客户端,用于浏览器和 node.js。
执行 POST 请求
axios.post('/YOUR_FULL_API_URL', {
data1: 'value1',
data2: 'value2'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
完整文档: https://axios-http.com/
NPM package 自述文件: https://www.npmjs.com/package/axios
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.