从客户端向服务器端发送路由和数据时。我没有在服务器端接收数据

时间:2018-12-04 05:45:06

标签: javascript node.js ionic3

我正在尝试将文件上传到服务器。目前,我正在上传图片。 这是我的客户端代码

 onClickfileupload(){
    let data={};
    let path="";
   let api_url = '/api/uploadFileFromIonicHome';
    this.fileChooser.open()
    .then(uri => 
    { 
      path= JSON.stringify(uri);
      alert(path);

   data={
      userEmail: this.userEmail,
      userName: this.userName,
      userRole: this.userRole,
      fileComment: this.desc,
      type: "file",
      fullFileName:'file-'+Date.now()+'.jpg'
  } 
  this.imagesProvider.uploadImage(path, data, api_url).then((res) => {
    let dataPassedBackObj = {
      reload: true,
      pathOfFile: path,
      typeOf: "picture",
      userName: this.userName, 
      fileComment: this.desc
    }
    alert("Successfully uploaded picture...");
    this.events.publish('toggleMenu');

  }, err => {
    alert(err.http_status);

    alert("There was error in uploading picture...");

  }); })
    .catch(e => alert(e));
    }

这是我的提供商,我正在使用该文件将文件上传到服务器端。 这是我的提供商代码

     uploadImage(img, data ,api_url) {
    alert("Uploading file...");
    // Destination URL
    let url = SERVER_HOST + api_url;
    // File for Upload
    var targetPath = img;
    console.log("line 28"+targetPath);
    var options: FileUploadOptions = {
      fileKey: 'image',
      chunkedMode: false,
      mimeType: 'multipart/form-data',
      params: data,
    };

    const fileTransfer: FileTransferObject = this.transfer.create();

    return fileTransfer.upload(targetPath, url, options);
  }

这是我获取路由的服务器端代码。但要求身体快要空了{}。 这是我的服务器端代码的一部分

app.post('/api/uploadFileFromIonicHome', uploadFromHome.single('image'), function(req, res) {
console.log('within /api/uploadFileFromIonicHome');
console.log(req.body.type);
console.log(req.body);
var userName = req.body.userName;
var userEmail = req.body.userEmail;
var userType = req.body.userRole;
var fileName = req.body.fileName;
var type = req.body.type;   
var comment = req.body.comment;
var fileComment = req.body.fileComment;

我正在空“ req.body”  和“ req.body.type未定义。” 这是我得到的错误 typeerror:无法将对象转换为原始值

1 个答案:

答案 0 :(得分:0)

  

使用connect-multiparty读取文件。参考link

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

app.post('/upload', multipartMiddleware, function(req, resp) {
  console.log(req.body, req.files);
  // don't forget to delete all req.files when done
});