背景
我尝试使用angular-file-upload模块将图像从localhost:3000上传到localhost:9000,我认为它们是不同的域,应属于 CORS (跨域资源共享) )。我看到this module supports CORS。我还遵循他们推荐的快速服务器设置here。但我仍然无法在请求中的body对象或files对象中看到任何内容。
问题
代码
/* ***************************** ANGULAR ***************************************** */
var myApp = angular.module('myApp', ['angularFileUpload']);
myApp.controller('MyCtrl', [ '$scope', '$upload', function($scope, $upload) {
$scope.$watch('files', function(files) {
if (files) {
for (var i = 0; i < $scope.files.length; i++) {
var file = $scope.files[i];
$scope.upload = $upload.upload({
url: 'http://localhost:9000/upload/',
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
}).success(function(data, status, headers, config) {
console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
});
}
}
});
}]);
/* ***************************** SERVER SIDE ***************************************** */
var multipart = require('connect-multiparty');
var express = require('express');
var bodyParser = require('body-parser')
var _ = require('underscore');
var path = require('path');
var app = express();
app.use(multipart({
uploadDir: './uploads'
}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(function (req, res, next) {
console.log(req.files); // {} why ????
console.log(req.body); // {} why ????
});
app.listen(9000);
答案 0 :(得分:1)
实际上,我通过使用名为cors的中间件来解决这个问题。所以服务器代码看起来像这样
var multipart = require('connect-multiparty');
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser')
var app = express();
app.use(multipart({
uploadDir: './uploads'
}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// cors middleware
app.use(cors());
app.use(function (req, res, next) {
console.log(req.files); // then there is something : )
next();
});
app.listen(9000);