Reactjs 对第三方的要求做出快速反应

Reactjs 对第三方的要求做出快速反应,reactjs,npm,Reactjs,Npm,我将skipThirdPartyRequests设置为true,但react snap已阻止所有请求。我知道这是正常行为,但我有自己的API,不知道如何将API请求发送到执行预渲染时react snap使用的同一主机(localhost:45678)。所以我在预渲染阶段向生产域发送了请求,但在启用skipThirdPartyRequests之后,这些请求被阻止。我需要skipThirdPartyRequests来禁用Google分析和其他服务 有没有办法在预渲染阶段使用启用的skipThirdP

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


有没有办法在预渲染阶段使用启用的skipThirdPartyRequests与自己的API进行通信?

我找到了解决方案。我们可以启动自己的express server并使用选项
{…,externalServer:true,port:/*服务器端口*/}
调用react snap的
运行
函数,然后react snap将不启动自己的服务器,只向
本地主机:{port}
发送请求。在我们的express服务器中,我们可以使用代理中间件
http代理中间件
将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()
    });