如何发送请求中的额外数据?

我想在http请求中发送itemId。 如何做到这一点,我会看到服务器上的要求?

这里是要求:

var fd = new FormData(); var itemId = scope.vm.item._id; fd.append('file', scope.files[0]); $http.post('http://localhost:8090/file-upload', fd, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }); 

服务器

  app.post('/file-upload', function(req, res, next) { console.log("received file"); var pathFile = ' '; var wId = "itemId"; var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, './uploads/attachments'); pathFile = file.originalname; }, filename: function (req, file,itemId, cb) { cb(null, file.originalname); console.log(itemId); } }); var upload = multer({ storage : storage }).single('file'); upload(req,res,function(err) { if(err) { return res.end("Error uploading file."); } //save file path in work items doc.attachments var path = './uploads/attachments/'+pathFile; res.end("File is uploaded"); }); 

服务代码添加。 如何获得服务器端的itemId?

Theres几个方法,你可以做到这一点,你可以在你的后期选项中设置params属性,并传入一个id作为属性的对象。

  var fd = new FormData(); var itemId = scope.vm.item._id; fd.append('file', scope.files[0]); $http.post('http://localhost:8090/file-upload', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined}, params: {id: itemId} }); 

您可以将JSONstring附加到FromData对象,如下所示。

fd.append('params',JSON.stringify({itemId:itemId}));

在服务器端,你会得到JSONstring的参数键。

简单地在参数中添加你的参数,并传递你的所有参数。

  $http.post('http://localhost:8090/file-upload', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined}, params: {id: scope.vm.item._id} }); 

希望这对你有用。