反应快照和skipThirdPartyRequests

时间:2019-12-19 18:59:28

标签: reactjs npm

我将skipThirdPartyRequests设置为true,但是react-snap阻止了所有请求。我知道这是正常行为,但是我有自己的API,却不知道如何在执行预渲染时将API请求发送到react-snap使用的同一主机(localhost:45678)。因此,我在预渲染阶段将请求发送到了生产域,但是在启用skipThirdPartyRequests之后,这些请求被阻止了。我需要skipThirdPartyRequests来禁用Google Analytics(分析)和其他服务。

是否有想法可以在启用renderPhirdPartyRequests的预渲染阶段与自己的API通信?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我们可以建立自己的快速服务器,并使用选项run调用react-snap的{..., externalServer: true, port: /*port of your server*/}函数,然后react-snap不会启动自己的服务器,而只会向localhost:{port}发送请求。在我们的Express服务器中,我们可以使用代理中间件http-proxy-middleware来将react-snap的请求代理到真实的后端。

我的片段代码:

const http = require('http');
const path = require('path');
const express = require('express');
const fallback = require("express-history-api-fallback");
const serveStatic = require("serve-static");
const proxy = require('http-proxy-middleware');

const {run} = require("react-snap");


let general = {
    "port": 45678,
    "externalServer": true,
    "skipThirdPartyRequests": true,
    "puppeteerArgs": [
        "--no-sandbox",
        "--disable-setuid-sandbox"
    ],
    source: "build",
    publicPath: '/'

};

const startServer = options => {
    const sourceDir = path.normalize(`${process.cwd()}/${options.source}`);
    const app = express()
        .use(proxy('/socket.io', { target: process.env.PRERENDERING_URI, changeOrigin: true, ws: true }))
        .use(options.publicPath, serveStatic(sourceDir))
        .use(fallback("200.html", { root: sourceDir }));

    const server = http.createServer(app);
    server.listen(options.port);
    return server;
};

let server = startServer(general);

Promise.resolve()
    .then(() => run({
        ...general,
        destination: "build/desktop",
        fixWebpackChunksIssue: false,
        userAgent: 'ReactSnap',
        "viewport": {
            "width": 1600,
            "height": 1200

        },
    }))
    .catch(console.error)
    .then(() => {
        server.close()
    });