我想将信息提交到在线服务器,它要求我使用 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]);
}
最佳答案
您尝试沿 formData 对象传递的附加数据应附加到 FormData
对象的 data
属性中。我曾经写过下面的函数。应该也适合你:
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 }
});
}
您可以将 .then
回调链接到该函数返回的对象。
尝试此操作,如果遇到任何问题请更新。
关于angularjs - FormData 附加不适用于 $http post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44540454/