我的后端和前端都在localhost上运行但在不同的端口上运行。我已经设置了CORS标头等,一切正常,即来自前端的所有请求(例如登录,创建用户帐户等)都可以正常工作。
现在,我一直在尝试将文件上传基本上放在http://code.ciphertrick.com/2015/12/07/file-upload-with-angularjs-and-nodejs/之后。但是,当我尝试上传文件时,我总是收到错误(例如在Firefox中)
阻止跨源请求:同源策略禁止在http://localhost:3000/uploads/读取远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin')。
我以为我已经正确设置了CORS标头,所以我不确定我做错了什么。也许我正在设置拦截器中的一个标头错误?任何帮助将不胜感激。
以下是相关代码:
Express Server
.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); // for the moment I allow all domains
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-type, Accept, X-Access-Token, X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
角度客户端设置
.config([
'$stateProvider',
'$urlRouterProvider',
'$httpProvider',
function($stateProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
...
}
]);
.factory('TokenInterceptor', ['$q', '$window', function($q, $window) {
return {
request: function(config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers['X-Access-Token'] = $window.sessionStorage.token;
config.headers['X-Key'] = $window.sessionStorage.username;
config.headers['Content-Type'] = "application/json";
}
return config || $q.when(config);
},
response: function(response) {
if (response.status === 401) {
// handle the case when the user is not authenticated
alert('You are not authenticated!');
...
}
return response || $q.when(response);
}
};
}]);
使用ng-file-upload
进行客户端上传HTML 的
<form name="up.upload_form">
Single Image with validations
<input
type="file"
ngf-select
ng-model="up.file"
name="file"
ngf-pattern="'image/*'"
accept="image/*"
ngf-max-size="20MB"
/>
Image thumbnail: <img style="width:100px;" ng-show="!!up.file" ngf-thumbnail="up.file"/>
<i ng-show="up.upload_form.file.$error.required">*required</i><br>
<i ng-show="up.upload_form.file.$error.maxSize">File too large
{{up.file.size / 1000000|number:1}}MB: max 20M</i>
<button type="submit" ng-click="up.submit()">submit</button>
<p>{{up.progress}}</p>
</form>
控制器的
var vm = this;
vm.submit = function(){
if (vm.upload_form.file.$valid && vm.file) {
vm.upload(vm.file); //call upload function
}
}
vm.upload = function (file) {
Upload.upload({
url: 'http://localhost:3000/uploads/',
data:{file:file}
}).then(function (resp) {
if(resp.data.error_code === 0){
$window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
} else {
$window.alert('an error occured');
}
}, function (resp) {
console.log('Error status: ' + resp.status);
$window.alert('Error status: ' + resp.status);
}, function (evt) {
console.log(evt);
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
vm.progress = 'progress: ' + progressPercentage + '% ';
});
};