【问题标题】:Cross-Origin Request Blocked while accessing api in nodejs application在nodejs应用程序中访问api时跨域请求被阻止
【发布时间】:2016-06-01 21:22:43
【问题描述】:

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

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).

代码的角部分在控制器中

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
            })
        }
    }
}) 

我正在使用它有

在 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并使用它,但还是同样的问题

【问题讨论】:

    标签: angularjs api cors directive


    【解决方案1】:

    您是从同一服务器还是从不同服务器渲染您的 html/客户端文件?

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

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 1970-01-01
      • 2021-08-30
      • 2020-12-22
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      相关资源
      最近更新 更多