连接 API - redux

Connection with API - redux

我正在用 React 和 Redux 构建一个项目,但是我无法连接我的 API。 我有这个,

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.

我该如何解决这个问题?

您需要在运行 http:/my-domain.dev/api

的本地网络服务器上设置 CORS headers

Headers发送:Access-Control-Allow-Origin: http://my-domain.dev/api

这可能对 Laravel github.com/barryvdh/laravel-cors

有帮助

当您在站点 A 上并调用(使用 ajax 请求)不同的服务器 B (different port, different domain name / ip address or different protocol) 时,浏览器期望 B 明确允许 A。 这是通过服务器 B 添加的 HTTP 响应 headers(和 OPTIONS 支持)完成的,参见 CORS (Cross-Origin Resource Sharing).

如果您必须能够从生产中的其他服务器调用您的 API,添加 CORS support in laravel 是个好主意。不需要的就不要加。

如果您的 API 来电是 simple enough and don't require cookies, you can configure your local Apache to just add the header Access-Control-Allow-Origin: *

否则,您应该从同一来源提供两种资源(API 和 React 前端)。