Webpack 开发服务器代理不工作 - ReactJS

Webpack dev server Proxy is not working - ReactJS

我想要 运行 我的项目 localhost:3000/upct/ROUTES

但我的 API 位于:http://desarrollo.com/api

我想在 Webpack 中使用代理选项,但它不起作用。我收到 CORS 和其他错误...我的代理配置如下:

    CONFIG.devServer = {
        //host: 'localhost',
        port: 3000,
        proxy: {
            '/api/**': {
                target: 'http://desarrollo.com/api',
                secure: false,
                changeOrigin: true
            }
        },
        contentBase: PATH.join(__dirname, '/src'),
        hot: true,
        inline: true,
        historyApiFallback: true/*,
        headers: { 
            'Content-Type': 'text/plain',
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
        }*/
    };

我的 AJAX 查询如下:

    $.ajax({
        url: "http://desarrollo.com/api",
        data: "",
        type:"GET",
        dataType: "JSON",
    })
    .done((respuesta) => {
        console.log(respuesta);

    }).fail(function(xhr, textStatus, errorThrown){
        console.log("XHR: ", xhr/*.responseText*/, "Text Status: ", textStatus + '\n' + "Error Thrown: ", errorThrown);
    })

我想代理是为了在没有 CORS 错误的情况下对我的 API 进行 AJAX 查询。但它不起作用。这里有什么问题?

谢谢。

使用代理时,您必须将请求发送到 localhost,以便代理可以将它们重定向到没有 CORS 的远程服务器。在你的 $.ajax() 中传递 url: "/api".

之后,当您 运行 您的应用在本地时,您的请求将发送到 http://localhost:3000/api,当它在 http://desarrollo.com 运行 时,它将发送请求到 http://desarrollo.com/api.

要向@GProst 响应添加更多内容,以下更改将起作用。

查找协议:

this.protocol = () => {
        let returnValue = 'https://';
        if (location.protocol !== 'https:') {
            returnValue = 'http://';
        }
        return returnValue;

};

查找主机名:

const hostName = window.location.hostname + (!window.location.port === false ? ':' + window.location.port : '');

必需 URL :

const URL = this.protocol() + hostName;

现在 URL 以上可用于 Ajax。

$.ajax({
    url: URL,
    data: "",
    type:"GET",
    dataType: "JSON",
})

这将适用于 webpack-dev-server 以及应用程序服务器,例如Apache.