I am getting a 400 Error when sending a form data to my node.js backend. It also gives me this error: Unexpected token - in JSON at position 0
I know that it isn't a problem with my node app because I can send the same data using Postman and it works perfectly.
This is my Angular method:
const formData = new FormData();
formData.append("db", $scope.item.db.toLowerCase());
formData.append(
"collection",
$("#collection")
.find("option:selected")
.text()
.toLowerCase()
);
formData.append("owner", JSON.parse(sessionStorage.getItem("user"))._id);
formData.append("name", $scope.item.name);
formData.append("description", $scope.item.description);
formData.append("year", $scope.item.year);
formData.append("photo", $("#picture")[0].files[0]);
$http.post("items/uploadItem", formData).then(function(response) {
console.log(response.data);
});
};
If you need any more information, please leave a comment and I would be happy to provide it.
CodePudding user response:
Most likely your response is formatted incorrectly. Is this your own api? Http methods attempt to parse responses as json. Try to change this line, JSON.parse(sessionStorage.getItem("user"))._id)
CodePudding user response:
The Angular $http service is expecting standard objects, not a form object. You are sending a serialised form object to your end point. Try
const formData = {
db: $scope.item.db.toLowerCase(),
// and the rest of your object properties.
};