首页 文章

我无法在Angular中获得REST服务响应

提问于
浏览
1

因此,我们公司内部不允许访问's VPN I can call the web service (which is a REST service) fine, on FF and Chrome. I need to connect to it from Angular 2 though. Now, I tried to call the REST service(which is inside VPN) from Angular 2, in several ways, and I am always getting the message about CORS("No ' Access-Control-Allow-Origin ' header is present on the requested resource. Origin ' http://localhost:4200' . 响应具有HTTP状态代码401. " in Chrome and "阻止跨源请求:同源策略不允许在http://webwassvc-test.servizi.gr-u.it/essigEAIM/rest/monitoring/integrations/all?pag=1读取远程资源 . (原因:CORS Headers 'Access-Control-Allow-Origin'缺失) . “在Firefox中 . ”我尝试将about:config:security.fileuri.strict_origin_policy设置为false,并且它没有知道它是什么 . 建议,好吗?

更新:我可以通过PHP作为中间件(localhost / angular2_site / file.php)访问REST服务并从中获取数据,但不能直接从angular(localhost:4200)获取数据 .

1 回答

  • 1

    使用代理或负载均衡器管理它的另一个选择 .

    如果您正在使用anuglar-cli进行开发,则可以使用angular-cli的Proxy To Backend支持 . --proxy-config

    来自angular-cli自述文件:

    假设我们在http:// localhost:3000 / api上运行了api服务器,我们希望所有对http:// localhost:4200 / api的调用都转到该服务器 . 我们在项目package.json旁边创建一个文件,名为proxy.conf.json,内容为{
    “/ api”:{
    “target”:“http:// localhost:3000”,
    “安全”:错误
    }
    }
    您可以在这里阅读更多关于webpack-dev-server代理设置的可用选项,然后我们将package.json文件的启动脚本编辑为“start”:“ng serve --proxy-config proxy.conf.json”,现在用npm start运行它

    因此,最后您可以将您的服务称为:

    getUsers() : Observable<any>{
      return this.http.get('/api/users').map(res => res.json());
    }
    

相关问题