簡體   English   中英

AngularJS + SailsJS ng文件上傳

[英]AngularJS + SailsJS ng-file-upload

您能否向我推薦一個Sails.Js + Angular.js的示例,用於將文件上傳到服務器,然后查看它們。 我已經審查了很多示例,但都不合適。 當我每次嘗試下載控制台時出現錯誤時:

XMLHttpRequest無法加載localhost:1337 / analyzes / upload。 對預檢請求的響應未通過訪問控制檢查:“ Access-Control-Allow-Origin”標頭包含無效值“”。 因此,不允許訪問Origin localhost:3000。

我的AngularJS控制器的一部分(帶有ng-file-upload模塊):

    $scope.upload = function (file) {
    Upload.upload({
        url: AppSettings.serverUrl+'/analyzes/upload',
        data: {file: file}
    }).then(function (resp) {
        console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
    }, function (resp) {
        console.log('Error status: ' + resp.status);
    }, function (evt) {
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    });
};

我的HTML:

<div class="button" ngf-select="upload($file)">Upload on file select</div>

還有我的Sails.JS控制器(我也有空模型):module.exports = {

  upload: function  (req, res) {
    req.file('analyzes').upload(function (err, files) {

      if (err)
        return res.serverError(err);

      return res.json({
        message: files.length + ' file(s) uploaded successfully!',
        files: files
      });
    });
  }
};

我覺得問題的根源是我使用單獨的URL來顯示網站(localhost:3000),而另一個用於Sails.Js(localhost:1337)。

我正在使用這個https://github.com/jakemmarsh/angularjs-gulp-browserify-boilerplate作為前端

為我的英語而哭。

你是對的; 問題與您的Sails應用有關,該應用不允許localhost:3000。 http://sailsjs.org/documentation/reference/configuration/sails-config-cors上查看文檔。

基本上,您需要通過CORS允許localhost:3000。 從上面的文檔

'/foo/bar': {
  target: 'FooController.bar',
  cors: {
    origin: 'http://foobar.com,https://owlhoot.com',
    methods: 'GET,PUT,POST,OPTIONS,HEAD'
  }
}

在您的情況下, originhttp:// localhost:3000 同樣不要忘記替換端點路由和target

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM