Flask + Nginx + React + Webpack 配置解決跨域問題

用 Flask 作後端開發單頁應用,webpack-dev-server 生成靜態文件在http://localhost:8080 下,Flask 頁面在 http://localhost:5000 下。html 頁面須要寫成:html

...
<script src="//localhost:8080/asserts/bundle.js"></script>
...

存在跨域問題,現用 nginx 將 80805000 端口代理到默認的 80 端口解決。看着也更優雅。webpack

webpack 配置:nginx

const url = "http://localhost:8080"

module.exports = {
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: `${url}/asserts/`,
    },
    devServer: {
        port: 8080,
        compress: true,
        hot: true,
        historyApiFallback: true,
        contentBase: path.join(__dirname, "dist"),
        publicPath: `${url}/asserts/`,
    }
    ...
}

nginx 配置web

server {
    listen 80;
    server_name localhost; 
    location / {
        # flask 代理
        proxy_pass http://127.0.0.1:5000;
    }

    location /asserts/ {
        # webpack-dev-server 代理
        proxy_pass http://127.0.0.1:8080/asserts/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        error_page 502 @start-webpack-dev-server;
    }

    location @start-webpack-dev-server {
        default_type text/plain;
        return 502 "Please start the webpack-dev-server first.";
    }
}
相關文章
相關標籤/搜索