【发布时间】:2018-10-14 10:26:28
【问题描述】:
我使用 Ajax 和 JSON 方法将 base64 图像字符串发送到 ExpressJS。在发送到 ExpressJS 之前,整个 JSON 使用 console.log 在客户端 Web 浏览器中显示是正确的。
由于长度限制,我无法在此处显示整个 JSON 字符串。但结果类似于以下输出:
{"map":"base64 String", "other":"abcdefghij"}
ExpressJS 大部分时间都可以接收整个 JSON 字符串。但有时结果如下:
ng", "other":"abcdefghij"}
或
{"map":"base64 Strin
更新:
客户端上传 JSON 到服务器:
$('#btn_floor_upload').click(function () {
var map_image_obj = new Image();
map_image_obj.src = URL.createObjectURL($('#select_map_file').prop('files')[0]);
$(map_image_obj).one('load', function () {
var canvas = document.createElement("canvas");
canvas.height = window.canvas_height;
canvas.width = window.canvas_width;
var ctx = canvas.getContext("2d");
ctx.drawImage(map_image_obj, 0, 0, canvas.width, canvas.height);
// above action for resizing image
var upload_data = {
map: canvas.toDataURL("image/jpeg", 0.2),
height: window.canvas_height,
width: window.canvas_width,
floor_name: $('#floor_name').val()
};
$.ajax({
type: "POST",
url: "/edit/upload_floor",
data: JSON.stringify(upload_data),
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 3000,
success: function (result) {
if (result.uploaded) {
$('#floor_list').append(new Option($('#floor_name').val(), result.floor_id));
$('#floor_name').val("");
$('#select_map_file').val("");
$('#btn_delete_floor').attr("disabled", false);
$('#floor_dialog').modal('toggle');
}
},
error: function () {
$.notify({
message: 'Server Error, Please upload the image again!'
}, {
type: 'danger',
delay: '5000'
});
$('#floor_dialog').modal('toggle');
}
});
});
});
服务器端: 错误发生在第 4 行。
upload_floor(req, res){
req.on('data', function(data) {
try {
var json = JSON.parse(data.toString());
var floor_id = buildingFloor.upload_map(json.floor_name, json.map, json.height, json.width, req.session.username);
res.send(JSON.stringify({floor_id: floor_id, uploaded:true}));
}catch(err){
console.log(err);
}
});
};
错误信息:
Unexpected token m in JSON at position 1
或
Unexpected end of JSON input sometimes
【问题讨论】:
-
SinLok,您是否尝试过将来自 express 服务器的 json 字符串化并在客户端解析。
-
@Vishnudev base64 图像字符串从客户端发送到服务器。不是服务器到客户端。我在发送操作之前使用 JSON.stringify。但是在网络浏览器中显示的整个字符串是正确的。
-
您可能需要展示如何在服务器端读取输入 JSON
-
您能否将客户端代码的 AJAX 部分发布到服务器上?
-
@Vishnudev 请参阅我的更新部分。
标签: javascript node.js ajax express