?yb? 2018-12-15 05:07 采纳率: 100%
浏览 190

NodeJS请求主体返回空{}

I have this javascript function that is supposed to upload a .json file to the server.

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 {}.

EDIT:

I'm passing the JSON as plain text. On the at console.log(data_blob) it prints exactly what I want to save. 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?

  • 写回答

1条回答 默认 最新

  • weixin_33719619 2018-12-15 05:34
    关注

    If you want to upload files to backend, you should try multer. It's really good and if you need I can post examples

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器