No' Access-Control-Allow-Origin'标头出现在请求的资源上。因此,不允许Origin' localhost'访问

时间:2017-11-20 10:37:31

标签: angularjs node.js express mean-stack

我想通过URL传递获取json数据。但它显示的错误如

Failed to load https://sample-dec42.firebaseapp.com/one.json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access.

解决此错误我使用了以下服务器和控制器代码

控制器:

     $http.get('https://sample-dec42.firebaseapp.com/one.json').then( function(response) {
                          $scope.resultValue = response.data;
                          console.log('successful');
                        document.write(JSON.stringify(response));
                          console.log(  $scope.resultValue);


               });

app.js:

var request = require('request');
app.use(function(req,response,next)
{
    response.header('Access-Control-Allow-Origin',"*");
    response.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
    response.header('Access-Control-Allow-Headers','Content-Type');
    next();


})

在这里,我创建了一个样本小提琴:Click Here to View

如何解决此错误。我在互联网上搜索过。但是,我仍然不知道为什么我一次又一次地得到这个错误。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

将“cors”模块导入您的项目,如果您使用Express,请使用它:

app.use(cors());

答案 1 :(得分:-1)

使用以下代码::

app.use(function (req, res, next) {
// Following headers are needed for CORS
   res.setHeader('access-control-allow-headers', 'Origin, X-Requested-With, Content-Type, Accept, ajax, access-key,backend,app_request,frontend, token,device');
   res.setHeader('access-control-allow-methods', 'POST,HEAD,GET,PUT,DELETE,OPTIONS');
   res.setHeader('access-control-allow-origin', '*');
   next();
});