node.js - 如何使用 https 模块在 Nodejs 中读取 POST 图像数据
问题描述
在不使用 Node.jsexpress
模块的情况下,我可以使用模块读取两个 POST 数据变量https
吗?
我的代码工作正常,只是我需要从请求中获取两个POST请求值(许可证和照片)。如何从 POST 请求中提取两个部分?
const https = require('https');
const fs = require('fs');
const options = {
secure: true,
key: fs.readFileSync('ssl/key.pem'),
cert: fs.readFileSync('ssl/public.pem'),
ca: fs.readFileSync('ssl/cap1_led_com.ca-bundle')
};
https.createServer(options, function (req, res)
{
let body = '';
if (req.method === 'GET' && req.url === '/')
{
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./http-form.html', 'UTF-8', (err, data) => {
if (err)
throw err;
res.write(data);
res.end();
});
}
else if (req.method === 'POST')
{
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(body, () => {
res.end();
});
});
}
else
{
res.writeHead(404, {'Content-Type': 'text/html'});
res.end(`<h1>404 ERROR could not find that Page</h1>`);
}
}).listen(443);
解决方案
有人在这里发布了答案,但后来令人惊讶地删除了它,这实际上有效:
const https = require('https');
const fs = require('fs');
const tmp = require('tmp');
const options = {
secure: true,
key: fs.readFileSync('ssl/key.pem'),
cert: fs.readFileSync('ssl/public.pem'),
ca: fs.readFileSync('ssl/capt1_tf.ca-bundle')
};
https.createServer(options, function (req, res)
{
let body = '';
if (req.method === 'GET' && req.url === '/')
{
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./http-form.html', 'UTF-8', (err, data) => {
if (err)
throw err;
res.write(data);
res.end();
});
}
else if (req.method === 'POST')
{
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
const map = {};
body.split('&')
.map((pair) => pair.split('='))
.forEach((splitPair) => {
map[splitPair[0]] = splitPair[1];
});
const decodeUriComponent = require('decode-uri-component');
tmp.file({ discardDescriptor: true },function _tempFileCreated(err, path, fd, cleanupCallback) {
if (err) throw err;
console.log(path);
fs.writeFile(path, decodeUriComponent(map.base64), 'base64', function(err) {
});
});
});
}
else
{
res.writeHead(404, {'Content-Type': 'text/html'});
res.end(`<h1>404 ERROR could not find that Page</h1>`);
}
}).listen(443);
推荐阅读
- e2e-testing - 如何在赛普拉斯 e2e 测试中右键单击以选择上下文菜单
- c++ - 如何制作一个简单的程序来输出两个符号的金字塔:一个在 C++ 中使用循环打印两次?
- azure - 为 Azure 多容器应用程序(多个存储库)设置 Azure Pipelines
- excel - 数据输入后的VBA保存延迟
- visual-studio - 无法从 Windows Parallels 在 Macbook 上运行 Xamarin.iOS 应用程序(无法安装代理)
- machine-learning - 为什么 Keras 顺序模型无法编译?
- laravel - 如何使用 ftp 将 laravel 部署到服务器
- android - Apk 未在 Google Playstore 中上传
- date - R 到 SAS 日期转换
- python - 如何将 JSON 文件也加载到 PSQL 数据库中