如何将这个PHP转换为express.js/node

How to convert this PHP to express.js/node

本文关键字:express js node 转换 PHP      更新时间:2023-09-26

>我正在尝试创建一个端点,该端点获取发布数据并将其保存到png文件中。这个 PHP 代码是这样做的:

if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
    // Remove the headers (data:,) part.  
    // A real application should use them according to needs such as to check image type
    $filteredData=substr($imageData, strpos($imageData, ",")+1);
    // Need to decode before saving since the data we received is already base64 encoded
    $unencodedData=base64_decode($filteredData);
    // Save file.  This example uses a hard coded filename for testing, 
    // but a real application can specify filename in POST variable
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
}

我是新来表达的,我有这个:

app.use (function(req, res, next) {
    var data='';
    req.setEncoding('utf8');
    req.on('data', function(chunk) { 
       data += chunk;
    });
    req.on('end', function() {
        req.body = data;
        next();
    });
});
app.post('/upload', function(req, res){
    var testData = req.body;
    return res.send(testData);
});

我得到一个空白对象。 即使实际数据正在发布。有人可以告诉我一种用 express 编写上述代码的好方法吗?

谢谢

所以从处理程序那里获取它:

var fs = require('fs');
app.post('/upload', function(req, res){
    var image = req.body;
    var noHeader = image.substring(image.indexOf(',') + 1);
    var decoded = new Buffer(noHeader, 'base64');
    fs.writeFile('testfile.png', decoded, function(err){
        res.send('done!');
    });
});