使用angularjs表单post(使用ngUpload上传文件)和nodejs服务器的跨域问题

时间:2013-08-19 09:12:09

标签: javascript node.js angularjs

我创建了一个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在带有端口3000的localhost上运行,因此调用是跨域的(尝试更改为端口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中,它被阻止,我无法使用它。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

如果您的浏览器支持,则可以使用CORS。由于您要发布数据,因此无法将其作为JSONP(仅支持GET请求)发送,但您可以使用其他workarounds