我创建了一个 AngularJS 应用程序,该应用程序连接到 NodeJS 服务器,该服务器使用AngularJS 的ngUpload指令上传文件。
问题是从服务器返回数据后,客户端被阻止
Blocked a frame with origin "http://localhost" from accessing a frame with origin "http://localhost:3000". Protocols, domains, and ports must match. ng-upload.min.js:14
Uncaught TypeError: Cannot read property 'body' of undefined
AngularJS 在 localhost 上运行,而 NodeJS 在 localhost 上运行,端口为 3000,因此调用是跨域的(尝试更改为端口 80,但没有用)
这是客户端的表单代码:
<form enctype="multipart/form-data" method="POST" action="http://localhost:3000/upload" name="iconForm" id="thumbnail_form" ng-upload>
<div class="submitFormRow fileUpload">
<span class="btn btn-warning uploadBtn" style="z-index: 99;">Upload resume</span>
<input type="file" class="input" name="file" tabindex="-1" size="12" id="file" style="z-index: 999;filter:alpha(opacity=0);">
<input type="hidden" value="{{PositionId}}" id="positionid" name="positionid"/>
<input type="hidden" value="{{user_fullName}}" id="fullname" name="fullname"/>
<input type="hidden" value="{{user_email}}" id="email" name="email"/>
<div class="clear"></div>
</div>
<div class="submitFormRow submitBtn">
<input type="submit" upload-submit="bar(content)" class="btn btn-danger" value="Submit"/>
</div>
<div>{{uploadResponse}}</div>
</form>
这是 NodeJS 服务器上的代码:
app.post('/upload', function (req, res) {
setTimeout(
function () {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
//res.type('application/json');
var positionId = req.body.positionid ? req.body.positionid : "-1";
var fullName = req.body.fullname ? req.body.fullname : "John Doe";
var email = req.body.email ? req.body.email : "default@default.com";
if (req.files.length == 0 || req.files.file.size == 0)
res.send({"success":false, message: "No File was uploaded", data:""});
else {
var fileType = req.files.file.name.split(".").pop();
if(!checkFileType(fileType)){
res.send({"success":false, message: "Invalid file type", data:""});
}
else {
var file = req.files.file;
fs.readFile(req.files.file.path,function(err,data){
var newPath = __dirname + "/uploads/user_" + new Date().getTime() + "_for_position_" + positionId +"." + fileType;
fs.writeFile(newPath, data, function (err) {
if(err){
res.send({"success":false, message: "file wasn't saved", data:""});
}
else {
var dbSaveCallback = function(err,result){
if(result){
res.send({"success":true, message: "file saved", data:newPath});
}
else {
res.send({"success":false, message: "file wasn't saved", data:""});
}
};
saveApplicantToDatabase(positionId,fullName,email,newPath,dbSaveCallback);
}
});
});
}
}
},
(req.param('delay', 'yes') == 'yes') ? 2000 : -1
);
});
服务器返回一个 jsonp 结果,其中包含数据,但在 ngupload.min 中,它被阻止了,我无法使用它。
我该如何解决这个问题?