在 nodejs 应用程序中访问 api 时阻止跨域请求

Cross-Origin Request Blocked while accessing api in nodejs application

我在 angularjs 中有一个指令,它对 nodejs api 进行服务调用,但是在访问它时我收到错误 has

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/search?search=aqqqqq. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Angular部分代码在控制器中

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.locationURL="http://localhost:8000/search";
});

app.directive('autoCompleteDirective',function($http){
    return{
        restrict:'A',
        scope:{
            url:'@'
        },
        link:function(scope,elm,attrs){
            elm.autocomplete({
                source:function(request,response){
                    $http({method:'get',url:scope.url,params:{search:request.term}}).success(function(data){
                        console.log("!!!!!!!!!!!!!!");
                        console.log(data);
                        response(data);
                    })
                },
                minLength:5
            })
        }
    }
}) 

我ui我正在用它有

在 nodejs 端,代码如下所示

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var port = process.env.PORT || 8000;
var router = express.Router();
var cors = require('cors');
var Schema = mongoose.Schema;
var router = express.Router();
var exec = require('exec');
app.use(bodyparser.json());
/*app.use(cors);*/

//establish the connection
var db=mongoose.connect('mongodb://localhost/book_publisherSearch');


//define the schema
var authorSchema = new mongoose.Schema(
    {
        authorId : Number,
        Description : String,
        firstName : String
    });

authorSchema.index({ firstName: 'text'});


var Authors= mongoose.model('Authors',authorSchema);

router.route('/search')
    .get(function(req,res){
        console.log(req.query.search);
        Authors.find({ $text : { $search : req.query.search }},function(err,authors){
            console.log("inside search");
            console.log(authors);
            res.send(authors);
        })
    })


app.use(router);
app.listen(port);

但我无法在客户端做出响应,请帮我弄清楚我没弄明白是不是我出错了

我尝试安装 cors 并使用它,但仍然是同样的问题

您是从同一服务器还是不同服务器呈现 html/client 文件?

从同一个 URL 呈现您的页面,您不会收到此错误。

如果它来自不同的服务器,您将收到跨源错误。 运行 来自两个不同的应用程序是要求,在您的 node.js 应用程序中添加允许跨源 header。

希望对您有所帮助。