[英]NodeJS req body returns empty {}
I have this javascript function that is supposed to upload a .json file to the server. 我有这个javascript函数,应该将.json文件上传到服务器。
function project_save_confirmed(input) {
if ( input.project_name.value !== _onco_settings.project.name ) {
project_set_name(input.project_name.value);
}
// onco project
var _onco_project = { '_onco_settings': _onco_settings,
'_onco_img_metadata': _onco_img_metadata,
'_onco_attributes': _onco_attributes };
var filename = input.project_name.value + '.json';
var json = JSON.stringify(_onco_project);
var data_blob = new Blob( [JSON.stringify(_onco_project)],
{type: 'text/json;charset=utf-8'});
//save_data_to_local_file(data_blob, filename);
upload_json_to_server(json, filename);
user_input_default_cancel_handler();
}
async function upload_json_to_server(data_blob, filename) {
console.log(data_blob);
$.ajax({
type: 'POST',
url: 'http://localhost:3000/upload',
body: data_blob,
contentType: 'text/json'
}).done(function (data) {
console.log(data);
});
}
On my server I have the route corresponding to the file upload 在我的服务器上,我有对应于文件上传的路由
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
const fs = require('fs');
const bodyParser = require("body-parser");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json({
extended: true
}));
app.post('/upload', function(req, res) {
console.log(req.body);
fs.writeFileSync('./data/oncofinder-' + Date.now() +'.json', req); //default: 'utf8'
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
But on my console.log(req.body)
the only thing I get is {}
. 但是在我的
console.log(req.body)
上,我唯一得到的是{}
。
EDIT: 编辑:
I'm passing the JSON as plain text. 我将JSON作为纯文本传递。 On the at
console.log(data_blob)
it prints exactly what I want to save. 在
console.log(data_blob)
它精确地打印了我要保存的内容。 I don't understand how the body can be empty since I'm printing right before I send it. 我不知道如何发送空的邮件,因为我是在发送邮件之前立即进行打印的。
Any idea what I'm doing wrong? 知道我在做什么错吗?
If you want to upload files to backend, you should try multer. 如果您想将文件上传到后端,则应尝试multer。 It's really good and if you need I can post examples
真的很好,如果您需要,我可以张贴示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.