如何编辑标题访问控制允许在浏览器中调用数据库Api?

时间:2017-04-23 01:24:03

标签: javascript mongodb

我希望使用快速API

从mongodb数据库中获取反向数据

的javascript

$scope.nmr=function(){
    $http.get("http://127.0.0.1:8081/Blogs")
    .then(function (response)
            {$scope.Blog = ((response.data).slice(0,8));
            });
            };

HTML

 <span style=" font-size:25px; ">معبد حتبسوت</span>
    <span style="margin-right:10%;" ng-repeat="x in Blog">
    <div star-rating rating-value="x.AvgRate" max="5"></div>
    </span>

server.js /原料药

 app.get('/Blogs', function (req, res) {
    MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //We are connected.
    console.log('Connection established to', url);

    db.collection('Blog').find().toArray(function (err, result) {
    if (err) throw err

    console.log(result);
    res.end( JSON.stringify(result));
     })
     }
     });
     }) 

此错误出现在浏览器中,但控制台中返回的数据

        [database server][1]

阻止跨源请求:同源策略禁止在http://127.0.0.1:8081/Blogs读取远程资源。 (原因:CORS标题'Access-Control-Allow-Origin'缺失)

1 个答案:

答案 0 :(得分:0)

你需要这样做:

var allowCrossDomain = function(req, res, next) {
        if ('OPTIONS' == req.method) {
          res.header('Access-Control-Allow-Origin', '*');
          res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
          res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
          res.send(200);
        }
        else {
          next();
        }
    };

    app.use(allowCrossDomain);

cors in express