跨源请求

时间:2017-01-30 12:56:31

标签: angularjs node.js express

我想从前端支持上传图片....我将使用ngFileUploader bower组件。 我的前端代码是:

function SampleController(SampleData,Upload,$http) {
      var vm = this;
      vm.uploadFiles = function(files, errFiles) {
        Upload.upload({
      url: "localhost:5000/upload", //webAPI exposed to upload the file
      data: {
        file: files
      }
    }).then(function(resp) {
      console.log(resp)});
    }

我将在其html文件中添加ngf-select。   它会显示错误 - XMLHttpRequest无法加载localhost:5000 / upload。交叉源请求仅支持协议方案:http,data,chrome,chrome-extension,https,chrome-extension-resource。   我怎么解决呢?

2 个答案:

答案 0 :(得分:0)

你需要添加这个:

header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Origin: *');

我的项目后端是laravel。所以,我把它包含在Route文件中。

答案 1 :(得分:0)

将cors过滤器作为中间件添加到您的应用程序

var app = require('express')();
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', ['GET', 'PUT', 'POST', 'DELETE']);
  next();
});

我建议您列出您允许的来源白名单。