2017-07-10 22 views
3

當我們將包括JSON內容的數據發送到外部API時,會發生Access-Control-Allow-Origin錯誤。這個問題的解決方案是使用x-www-form-urlencoded content。 反正有沒有使用JSON呢?如何使用角度2請求數據

JSON內容:

this.http.post('/api/login', { 
     email: email, 
     password: pass 
    }).map(res => res.json()) 
     .subscribe(response => { 
     console.log(response); 
     } , error => console.error(error)); 
    } 

x-www-form-urlencod

this.headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
    this.options = new RequestOptions({ headers: this.headers, method: 'post'}); 
    return this.http.post('/api/login', "[email protected].com&password=123", this.options) 
     .map(res => res.json()) 
     .map(user => { 
      if (user) { 
       console.log(user); 
      } 
      return !!user ; 
     }); 
} 

其他解決方案:

1.安裝訪問控制允許來源擴展的Chrome
2.lunch網頁API在localhost bu尋找另一種方式
3.啓用IIS7上的CORS

但問題沒有解決!

+2

是您需要啓用它在你的API –

+0

@RahulSingh CORS由web.config中一個CORS問題已啓用,問題是不解決 – Allahyar

+0

檢查後在郵遞員。 默認情況下/ token是獲取mvc令牌的URL – Habeeb

回答

1

WebConfig:

<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol>​ 

WebApiConfig:

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET,POST,PUT,DELETE"); 
config.EnableCors(cors); 
+0

XMLHttpRequest無法加載/ api/login。對預檢請求的響應不會通過訪問控制檢查:「Access-Control-Allow-Origin」標頭包含多個值'*,*',但只允許有一個值。因此不允許訪問Origin'http:// localhost:4200'。 – Allahyar