提问者:小点点

平均堆栈文件上传


我正在开发一个MEAN堆栈Web应用程序,我想使用ng2文件上传文件。这是我的Angular 2代码。

classroom.component.html

    <input type="file" class="form-control" name="single" ng2FileSelect [uploader]="uploader" />
    <button type="button" class="btn btn-success btn-s"
                  (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
            <span class="glyphicon glyphicon-upload"></span> Upload all
          </button><br />

教室组件ts

uploader:FileUploader = new FileUploader({url: "http://localhost:3000/api/material/create-material"});

在服务器中.js

app.use(cors());
app.use('/api',api);
app.use('/api/material',material);

和材料.js

var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './uploads/');
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now();
        cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
    }
});

var upload = multer({ //multer settings
    storage: storage
}).single('file');

router.post('/create-material',passport.authenticate('jwt', {session: false}),function (req, res) {

    upload(req,res,function(err){
        console.log(req.file);
        if(err){
            res.json({error_code:1,err_desc:err});
            return;
        }
        //res.json({error_code:0,err_desc:null});
    });
});

上传文件时出现以下错误

XMLHttpRequest无法加载http://localhost:3000/api/material/create-material.对预检请求的响应未通过权限改造检查:当请求的凭据模式为包含时,响应中的'Access-Control-Allow-Origin'标头的值不能是通配符'*'。因此不允许访问Origin'http://localhost:4200'。由XMLHttpRequest发起的请求的凭据模式由with Creentals属性控制。

这是什么原因?


共3个答案

匿名用户

将以下内容添加到您的 nodejs 中间件中 -

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);

    next();
});

CORS支持*、null或根据-

服务器需要使用正则表达式验证源标头,然后您可以在访问控制允许源响应标头中回显源值。

匿名用户

这里的问题是您正在运行两个应用程序

    < li >端口号为4200的Angular 2应用程序 < li >表示端口号为3000的堆栈应用程序

因此,当Angular 2应用程序试图调用端口号为“3000”的堆栈应用程序时,浏览器会抱怨,因为它将被视为跨域ajax。为了解决跨域ajax,你必须在你的MEAN stack应用程序中添加以下代码行。

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

如果你真的不喜欢这样做,那么你必须采取以下步骤。

>

  • 首先构建角度应用程序,以使用“ng build”直接在 MEAN 堆栈应用程序下部署。
  • 这将在角度应用程序中生成“dist”文件夹。
  • 将此 dist 文件夹移动到 MEAN 堆栈应用程序的根文件夹下,并添加以下代码行

    app . use(express . static(path . join(_ _ dirname,' dist '),{ index:false });< br> app.get('/'),function (req,RES){ RES . sendfile(path . join(_ _ dirname '/dist/index . html ');});

    通过执行上述步骤,我们只运行一个在 MEAN 堆栈下的应用程序,前端将从 dist 文件夹中的角度生成的标记提供。

  • 匿名用户

    ng2-file-upload具有为每个文件指定withcredentials的选项。

    覆盖< code>onAfterAddingFile并为每个文件设置< code > with credentials = false 。

    例如:< code > this . uploader . onafteraddingfile =(file item:any)= 1

    这会解决你的问题。更多详情:ng2-file-upload/src/file-upload/file-item . class . ts