gpt4 book ai didi

json - AngularJS 未在 Http POST 中设置正确的内容类型

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:13 27 4
gpt4 key购买 nike

所以我尝试将 mp3 文件上传到 NodeJS 服务器。我正确地看到了文件数据和所有内容,因此我知道我的模型是正确的,但每次发送 http post 时,我都会收到无效的 JSON 错误。这很令人困惑,因为我已将内容类型设置为未定义和 multipart/form-data,并且无论何时查看控制台,我仍然看到在请求 header 中内容类型设置为 application/json。这是我用来上传的代码:

模板:

<form>
<div class="form-group">
<label name="type-label" for="type">Type</label>
<select name="type" ng-model="data.type">
<option value="music">Music</option>
<option value="image">Image</option>
<option value="video">Video</option>
</select>
</div>
<div class="form-group">
<label name="name-label" for="name">Name</label>
<input type="text" name="name" ng-model="data.name" />
</div>
<div class="form-group">
<label name="description-label" for="description">Description</label>
<input type="text" name="description" ng-model="data.description" />
</div>
<div>
<input type="file" upload-file="file"/>
</div>
<div class="form-group">
<div class="btn btn-primary" ng-click="upload()">Select File</div>
</div>
</form>

服务:

angular.module('app').factory("UploadService", ['$http',
function($http) {
return {
upload: function (file, data) {
var fd = new FormData();
fd.append('file', file);
return $http({
method: 'POST',
url: '/upload/' + data.type,
data: fd,
transformRequest: angular.identity,
headers: {
'Content-Type': 'multipart/form-data'
}
})
.success(function(){
//Do something.
})
.error(function(){
//Do something.
});
}
}
}
]);

Controller :

angular.module('app').controller('UploadController', ['$scope', 'UploadService',
function($scope, UploadService) {
$scope.data = {};
$scope.upload = function() {
console.log($scope.file);
UploadService.upload($scope.file, $scope.data);
};
}
]);

最后,我什至编写了一些辅助配置来尝试强制使用 http 帖子的默认内容类型。

助手:

angular.module('app').config(function($httpProvider) {
$httpProvider.defaults.headers.post = { 'Content-Type' : 'multipart/form-data' };
});

此时我非常不知道该怎么做,因此任何建议/帮助将不胜感激。或者任何有关上传 MP3 的一般提示(如果有比这更简单的方法)。谢谢!

最佳答案

试试这个

$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

关于json - AngularJS 未在 Http POST 中设置正确的内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32042383/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com