2016-11-20 104 views
1

我正在用react和redux構建一個項目,但我無法連接到我的API。 我有這個,連接API - redux

componentDidMount() { 
    const {dispatch} = this.props; 
    dispatch(fetchByQuerystring()); 
} 

fetchByQuerystring是:

export function fetchByQuerystring() { 
    return function(dispatch) { 

     return fetch(`http://my_domain.dev/api`) 
      .then(response => response.json()) 
      .then(json => dispatch(receiveByQuerystring(json))); 
    } 
} 

當我運行它,我得到這個錯誤:

Fetch API cannot load http://my-domain.dev/api . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我怎樣才能解決這個問題?

回答

1

當你在一個站點A上並且呼叫另一個服務器B(different port, different domain name/ip address or different protocol)時,瀏覽器期望B明確允許A. 這是通過服務器B添加的HTTP響應頭來實現的(並且支持OPTIONS),見CORS (Cross-Origin Resource Sharing)

如果您必須能夠從生產中的其他服務器調用您的API,那麼添加CORS support in laravel是個不錯的主意。如果你不需要它們,不要添加它們。

如果你的API調用是simple enoughdon't require cookies,你可以配置你的本地Apache爲add the headerAccess-Control-Allow-Origin: *

否則,您應該從同一個來源提供兩種資源(API和反應前端)。

0

你需要在你的本地網絡服務器設置CORS頭運行HTTP:/my-domain.dev/api

頭派:Access-Control-Allow-Origin: http://my-domain.dev/api

這可以幫助Laravel github.com/barryvdh/laravel-cors