解決跨域No 'Access-Control-Allow-Origin' header is present on the requested resource.

用angular發起http.get(),訪問後端web API要數據,結果chrome報錯:跨域了html

Access to XMLHttpRequest at 'http://127.0.0.1:3000/XXX' 
from origin 'http://127.0.0.1:4200' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

此時後端nodejs顯示返回值正常。只是瀏覽器給攔截了。前端

 

參考https://www.cnblogs.com/relucent/p/4274158.htmlnode

什麼是跨域web

當兩個域具備相同的協議(如http), 相同的端口(如80),相同的host(如www.google.com),那麼咱們就能夠認爲它們是相同的域(協議,域名,端口都必須相同)。chrome

跨域就指着協議,域名,端口不一致,出於安全考慮,跨域的資源之間是沒法交互的docker

 解決方法很簡單,在服務器端的response裏添加header,容許前端指定的主機訪問express

具體到express 參考 https://www.cnblogs.com/ae6623/p/4433143.htmljson

app. route( "/XXX")
  . get(jsonParser, ( req, res) => {
    //do something
    const content = 'OK'
    res.set({'Access-Control-Allow-Origin': 'http://127.0.0.1:4200'})
      .send(content)
  })
注意要包括 http://,和端口號,最好把這些寫在一個配置文件裏,在nodejs啓動時加載進來,便於在docker等容器裏用的時候修改前端的IP和端口
相關文章
相關標籤/搜索