【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://localhost:8100'
【发布时间】:2017-09-04 02:19:53
【问题描述】:

server.js 我声明了权限的地方

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.js

angular.module('app', ['ionic', 'ui.router'])

.config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){
    $urlRouterProvider.otherwise('/');
    $stateProvider
    .state('view',{
      url:'/',
      templateUrl:'js/components/view/view.html',
      controller:'viewCtrl'
    })

}))

view.js

.controller('viewCtrl',['$scope','$state','$http',function($scope,$state,$http)
{   

    $scope.pics=[];
    $http.get('http://localhost:8080/getNewPhoto').then(function(response){
        $scope.pics=response.data;
    },function(err)
    {
        console.error("There's an error"+err);
    })
}])

请帮我解决这个问题,我已经尝试了所有可能的解决方案,但问题仍然存在

【问题讨论】:

    标签: javascript angularjs node.js ionic-framework


    【解决方案1】:

    您必须添加一个重要的标题。将该行添加到服务器脚本:

    res.header('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT');
    

    【讨论】:

    • 你确定在 8080 端口上运行你的 nodejs 服务器吗?可能是tomcat或者其他使用这个端口的服务器
    • 是的,我在 8080 上运行我的服务器并尝试从端口 8100 访问它,但它不工作
    • 这真的很有趣。您可以通过 Postman 或直接从 Web 浏览器访问该服务吗?
    • 现在它正在使用 cors 模块工作,但它没有显示任何像我想调用 getPhotos 并且它没有显示
    • @kodmanyaga only server.js is missing else other code is present here
    【解决方案2】:

    只需使用cors module的express就可以了:

    var express = require('express')
    var cors = require('cors')
    var app = express()
    
    app.use(cors())
    

    【讨论】:

    • 我需要将 cors 添加到 pakage.json @lin
    • @AsadArshad 很好,因此修复了 cors 问题。请创建一个新问题,包括您的下一个问题。我要去那里接。请将您的节点部分添加到新问题中。一个指向新问题的链接会很好:) 请把它作为评论发布
    猜你喜欢
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2013-12-24
    相关资源
    最近更新 更多