将图像从html发送到node.js

时间:2018-06-04 07:34:34

标签: html node.js

您好我正在从视频中捕获帧并在Image中转换它。但是,当我将此图像传递给server.js时,我无法访问它并在控制台上将其类型视为未定义。这是我的脚本代码:

var canvas= document.getElementById("canvs");
var video=document.getElementById("videoElement");
var png= new Image();
var imcanvas = canvas.getContext("2d");
imcanvas.drawImage(video, 0,0 , canvas.width,canvas.height);	
png = canvas.toDataURL("image/png");
var json={"name":png};
jQuery.ajax({
	url: "/demo",
	type: "POST",
	data:json,
	processData: false,
	cache: false,
	success: function(reponse) {
	  if(reponse) {
	    console.log(reponse);
	  } else {
	    console.log('Error');
	  }
	}
});

这是我的server.js

var express = require('express');
var cv = require('./public/opencv');
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
	res.sendFile( __dirname + "/" + "index.html" );
});
app.post('/demo', (req,res)=>{
	console.log(typeof(req.body.name));
});
var server = app.listen(8081, function () {
	var host = server.address().address;
	var port = server.address().port;
});

2 个答案:

答案 0 :(得分:1)

这可能是身体的限制。

您可以做的是设置身体分析器限制,如下所示:

 app.use(bodyParser.urlencoded({
    limit: '50mb',
    extended: true
 }));

如果它仍未定义,请尝试在请求中添加dataType prop并对json数据进行字符串化。例如:

var json={"name":png};

jQuery.ajax({
    url: "/demo",
    dataType  : 'json',
    type: "POST",
    data: JSON.stringify(json),
    processData: false,
    cache: false,
    success: function(reponse) {
        if(reponse) {
            console.log(reponse);
        } else {
            console.log('Error');
        }
    }
})

答案 1 :(得分:1)

谢谢@ FewFlyBy。你回答了,我在server.js中添加了一个额外的声明。我能够这样做:

         //above codes
        jQuery.ajax({
                url: "/demo",
                type: "post",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(json),
                success: function (reponse) {
                    if (reponse) {
                        console.log(reponse);
                    } else {
                        console.log('Error');
                    }
                }
                });

并在server.js

    //require statements
    app.use(bodyParser.json({limit: '50mb'}));
    app.use(bodyParser.urlencoded({
       limit: '50mb',
       extended: true
    }));
    app.post('/demo', (req, res) => {
    const base64data=req.body.image;
    }