角度2:交叉原点错误

时间:2017-04-25 07:47:15

标签: angular

在角度2中,我得到交叉原点错误。我正在通过使用angular cli的ng服务运行项目

无法解决此问题,因为当我在浏览器中打开XML文件链接时它完全打开但是当我尝试在服务中访问它时它给了我错误

// data service file

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/operator/map';
import 'rxjs/operator/catch';
import 'rxjs/observable/throw';
import { xml2js } from 'xml2js';

@Injectable()
export class DataService {
//parser = new xml2js.Parser({explicitArray : false});
  constructor(private http: Http) { }

  getLoginData(){
    return this.http.get('https://api.myjson.com/bins/zsjzj')
      .map((data:Response) => data.json())
      .catch(this.getError);
  } 

 /* getXML(){
    return this.http.get('http://www.xmlfiles.com/examples/note.xml')
                .flatMap(res=>{
                        return Observable.fromPromise(this.getJSON(res.text()))
                })
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }*/
createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be7-9655-7ef7d7bf9d20')); 
  }

  xml2json(xml, tab) {
   var X = {
      toObj: function(xml) {
         var o = {};
         if (xml.nodeType==1) {   // element node ..
            if (xml.attributes.length)   // element with attributes  ..
               for (var i=0; i<xml.attributes.length; i++)
                  o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString();
            if (xml.firstChild) { // element has child nodes ..
               var textChild=0, cdataChild=0, hasElementChild=false;
               for (var n=xml.firstChild; n; n=n.nextSibling) {
                  if (n.nodeType==1) hasElementChild = true;
                  else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
                  else if (n.nodeType==4) cdataChild++; // cdata section node
               }
               if (hasElementChild) {
                  if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                     X.removeWhite(xml);
                     for (var n=xml.firstChild; n; n=n.nextSibling) {
                        if (n.nodeType == 3)  // text node
                           o["#text"] = X.escape(n.nodeValue);
                        else if (n.nodeType == 4)  // cdata node
                           o["#cdata"] = X.escape(n.nodeValue);
                        else if (o[n.nodeName]) {  // multiple occurence of element ..
                           if (o[n.nodeName] instanceof Array)
                              o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                           else
                              o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                        }
                        else  // first occurence of element..
                           o[n.nodeName] = X.toObj(n);
                     }
                  }
                  else { // mixed content
                     if (!xml.attributes.length)
                        o = X.escape(X.innerXml(xml));
                     else
                        o["#text"] = X.escape(X.innerXml(xml));
                  }
               }
               else if (textChild) { // pure text
                  if (!xml.attributes.length)
                     o = X.escape(X.innerXml(xml));
                  else
                     o["#text"] = X.escape(X.innerXml(xml));
               }
               else if (cdataChild) { // cdata
                  if (cdataChild > 1)
                     o = X.escape(X.innerXml(xml));
                  else
                     for (var n=xml.firstChild; n; n=n.nextSibling)
                        o["#cdata"] = X.escape(n.nodeValue);
               }
            }
            if (!xml.attributes.length && !xml.firstChild) o = null;
         }
         else if (xml.nodeType==9) { // document.node
            o = X.toObj(xml.documentElement);
         }
         else
            alert("unhandled node type: " + xml.nodeType);
         return o;
      },
      toJson: function(o, name, ind) {
         var json = name ? ("\""+name+"\"") : "";
         if (o instanceof Array) {
            for (var i=0,n=o.length; i<n; i++)
               o[i] = X.toJson(o[i], "", ind+"\t");
            json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]";
         }
         else if (o == null)
            json += (name&&":") + "null";
         else if (typeof(o) == "object") {
            var arr = [];
            for (var m in o)
               arr[arr.length] = X.toJson(o[m], m, ind+"\t");
            json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}";
         }
         else if (typeof(o) == "string")
            json += (name&&":") + "\"" + o.toString() + "\"";
         else
            json += (name&&":") + o.toString();
         return json;
      },
      innerXml: function(node) {
         var s = ""
         if ("innerHTML" in node)
            s = node.innerHTML;
         else {
            var asXml = function(n) {
               var s = "";
               if (n.nodeType == 1) {
                  s += "<" + n.nodeName;
                  for (var i=0; i<n.attributes.length;i++)
                     s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\"";
                  if (n.firstChild) {
                     s += ">";
                     for (var c=n.firstChild; c; c=c.nextSibling)
                        s += asXml(c);
                     s += "</"+n.nodeName+">";
                  }
                  else
                     s += "/>";
               }
               else if (n.nodeType == 3)
                  s += n.nodeValue;
               else if (n.nodeType == 4)
                  s += "<![CDATA[" + n.nodeValue + "]]>";
               return s;
            };
            for (var c=node.firstChild; c; c=c.nextSibling)
               s += asXml(c);
         }
         return s;
      },
      escape: function(txt) {
         return txt.replace(/[\\]/g, "\\\\")
                   .replace(/[\"]/g, '\\"')
                   .replace(/[\n]/g, '\\n')
                   .replace(/[\r]/g, '\\r');
      },
      removeWhite: function(e) {
         e.normalize();
         for (var n = e.firstChild; n; ) {
            if (n.nodeType == 3) {  // text node
               if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
                  var nxt = n.nextSibling;
                  e.removeChild(n);
                  n = nxt;
               }
               else
                  n = n.nextSibling;
            }
            else if (n.nodeType == 1) {  // element node
               X.removeWhite(n);
               n = n.nextSibling;
            }
            else                      // any other node
               n = n.nextSibling;
         }
         return e;
      }
   };
   if (xml.nodeType == 9) // document node
      xml = xml.documentElement;
   var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
   return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
}

getCompanies() {
  	var headers = new Headers();
  	this.createAuthorizationHeader(headers);
  	headers.append('Accept', 'application/xml');

  	return this.http.get('https://angular2.apispark.net/v1/companies/', {
      headers: headers
    }).map(res => JSON.parse(this.xml2json(res.text(),'  ')));
  }

  private getError(error: Response):Observable<String>{
      return Observable.throw(error.json() || 'Server Issue');
  }


}
//error

OPTIONS http://172.21.103.105:15871/cgi-bin/blockpage.cgi?ws-session=2053590089 404 (Not Found)
:4200/login:1 XMLHttpRequest cannot load http://172.21.103.105:15871/cgi-bin/blockpage.cgi?ws-session=2053590089. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.
core.es5.js:1085 ERROR Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers…}
defaultErrorLogger @ core.es5.js:1085
ErrorHandler.handleError @ core.es5.js:1145
next @ core.es5.js:4774
schedulerFn @ core.es5.js:3848
SafeSubscriber.__tryOrUnsub @ Subscriber.js:234
SafeSubscriber.next @ Subscriber.js:183
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3834
NgZone.triggerError @ core.es5.js:4205
onHandleError @ core.es5.js:4166
webpackJsonp.579.ZoneDelegate.handleError @ zone.js:369
webpackJsonp.579.Zone.runTask @ zone.js:168
ZoneTask.invoke @ zone.js:460

2 个答案:

答案 0 :(得分:1)

问题简介

Access-Control-Allow-Origin CORS (跨源资源共享)机制的一部分,该机制为Web服务器提供跨域访问控制。它可以保护您的应用/网站免受 CSRF (跨站请求伪造)。

Ow和它由浏览器强制执行

CORS / CSRF

问题

预检请求的响应未通过访问控制检查:否&#39; Access-Control-Allow-Origin &#39;所请求的资源上存在标题来源&#39; null&#39; 因此不允许访问。响应的HTTP状态代码为404.

您的后端(172.21.103.105:15871)说:您无法从其他域获取数据。

要解决此问题,您必须编辑后端网络服务器配置,以允许您的前端应用程序从您的后端查询数据(相同的IP不同的端口===不同的域)

您使用什么作为后端Web服务器?如果您提供,我将按照要遵循的步骤编辑我的帖子。但你可以很容易地谷歌。

答案 1 :(得分:1)

由于您使用的是Angular CLI(使用webpack),您可以将前端应用程序代理到后端。这将“欺骗”(实际上是代理)到后端,以认为您的前端请求来自同一个域。

如果您尝试访问的服务器URL仅允许来自同一域的请求,并且您的应用程序将在同一域上运行,则此解决方案很好。

含义 - 如果您在生产中部署了应用程序,它将与您正在调用的服务托管在同一个域中 - 这是一种很好的方法。如果该服务是第三方服务,不会与您的应用程序托管在同一个域中,那么无论如何您都会收到来自托管应用程序的CORS错误。

您可以通过创建包含以下内容的代理配置文件来设置代理:

{
  "/api": {
    "target": "_your_backend_ip_",
    "secure": false
  }
}

然后使用这样的npm脚本为您的应用程序提供服务:

"start": "ng serve --proxy-config _your_proxy_config_.json"

查看文档HERE