FormData附加不与$ http帖子一起使用

时间:2017-06-14 09:15:14

标签: angularjs multipartform-data

我想将信息提交给在线服务器,它要求我使用FormData发送信息。 所以我正在使用以下函数

var my_app = angular.module("my-app",[])
my_app.controller("MainController", function($scope, $http){
    $scope.master = {title: "Title",desc: "Desctibe", tags: ["One","Two"], category: ["1","2"] };
    var url = "http://freedoctor.southeastasia.cloudapp.azure.com/api/forum/create";
    var config = {"headers":{"Authorization":"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU5MzEwNDUxZjk3MjJmZTQyODE1NTIxYSIsInJvbGUiOiJwYXRpZW50IiwiaWF0IjoxNDk3NDE4ODA3fQ.ODrSlYwxvrPb93IzHW3s-7NIVFsOL4pKzqZx8yMqWWE"}};

    $scope.booking = function(){
        $scope.title=$scope.user.title;
        $scope.desc=$scope.user.desc;
        $scope.tags=$scope.user.tags;
        $scope.category=$scope.user.category;
        $scope.askedTo=$scope.user.askedTo;
        var info = new FormData();
        info.append("title", $scope.title);
        info.append("desc", $scope.desc);
        info.append("tags", $scope.tags);
        info.append("category", $scope.category);


        $http.post("http://localhost:8080/"+url, info, config).then(
        function(response){
            console.log(response);
            $scope.reply = response.data;
            },
            function(response){
                console.log(response);
                $scope.reply = response.data;
            });
    }

    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});

因此,每当我致电预订功能时,我都会收到内部服务器错误

SyntaxError: Unexpected token -
at parse (/home/freedoctor/fdhbackend/node_modules/body-parser/lib/types/json.js:83:15)
at /home/freedoctor/fdhbackend/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/home/freedoctor/fdhbackend/node_modules/raw-body/index.js:262:16)
at done (/home/freedoctor/fdhbackend/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/home/freedoctor/fdhbackend/node_modules/raw-body/index.js:307:7)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)

我知道FormData正在运行,因为我用这个

检查了它
for (var pair of info.entries()) {
  console.log(pair[0]+ ', ' + pair[1]); 
}

1 个答案:

答案 0 :(得分:2)

您尝试传递给formData对象的其他数据应附加到something对象的data属性。我曾经写过以下函数。应该也适合你:

FormData

您可以通过此函数将this.uploadFile = function (url, dataToUpload) { var data = new FormData(); data.append("file", dataToUpload.file); //if you want to upload files along, else ignore this line data.append("data", angular.toJson(dataToUpload.data)); //you can pass an object containing additional data and then append it here to the data property return $http.post(url, data, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }); } 回调链接到返回的对象。

如果您遇到任何问题,请尝试此操作并进行更新。