Я могу получить доступ к Application-2 либо напрямую, либо через IFRAME Application-1. Однако, когда я использую iframe Application-1, оно должно пройти через несколько серверов, чтобы достичь приложения-2, что-то вроде следующего. < /P>
Код: Выделить всё
Application-1, пока я могу получить доступ к Application-2 непосредственно, я не могу получить доступ, используя Application-1, используя iframe. Код> Файл, который обслуживает приложение-2 и работает на Server-3 .
Код: Выделить всё
const createError = require("http-errors");
const express = require("express");
const cors = require('cors')
const path = require("path");
const fs = require("fs");
const cookieParser = require("cookie-parser");
// Server-static middleware
const {
appLogger,
expressLogger,
expressErrorLogger,
} = require("./lib/logger");
const {corsOptionsDelegate} = require("./routes/corsDelegate");
const app = express();
app.disable("x-powered-by");
app.options('*', cors());
// serves static pages
app.use("/application-2/static", express.static(path.join(__dirname, "public")));
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(expressLogger);
app.use(expressErrorLogger);
app.use(cookieParser());
app.use(
express.static(path.join(__dirname, ".", "webapp")),
(req, res, next) => {
try {
decodeURIComponent(req.url);
return next();
} catch (err) {
return res.status(400).json({message: "Invalid request"});
}
}
);
const managementRouter = require("./routes/management");
app.use("/application-2/management", managementRouter);
// serves the application-2 app
app.use("/application-2", express.static(path.join(__dirname, ".", "webapp")));
// connect to the "src/routes" directory
const routersPath = path.join(__dirname, "routes/v1");
// read all files in the "/src/routers" directory
fs.readdirSync(routersPath).forEach((file) => {
if (file.endsWith(".js")) {
// dynamically import the router module
const routerModule = require((path.join(routersPath, file).replace(".js","")));
// register the router
app.use(routerModule);
}
});
app.get("/application-2/unauthorized", cors(corsOptionsDelegate), function (req, res, next) {
res.status(403);
res.sendFile(path.resolve(__dirname, ".", "views", "unauthorized.html"));
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handling
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error", {title: "ABC Images | application Search"});
});
module.exports = app;
Код: Выделить всё
app.use("/application-search", createProxyMiddleware({
target: "http://localhost:9012",
changeOrigin: true,
logLevel: 'debug',
pathRewrite: (path, req) => {
// Extract the query string from the original URL
const queryString = req.url.split('?')[1] || "11x";
// Rewrite the path to include the query string
return `/?${queryString}`;
},
onProxyReq: (proxyReq, req, res) => {
let cookieArray = [];
try {
// Split the cookies into an array and log them
const cookies = req.headers.cookie || "";
cookieArray = cookies.split(';').map(row => {
return row.trim();
});
} catch (error) {
console.error('Error processing cookies:', error);
}
//const tokenCookie = cookieArray.find(row => row.startsWith('ckns_pp_id=')) || "";
const tokenValue = tokenCookie.split('=')[1].trim();
// Add custom headers if needed
proxyReq.setHeader('Authorization', `Bearer ${tokenValue}`);
}
}));
Код: Выделить всё
app.use("/", createProxyMiddleware({
target: "https://xxx.co.uk/application-2",
changeOrigin: true,
logLevel: 'debug',
pathRewrite: (path, req) => {
// Extract the query string from the original URL
const queryString = req.url.split('?')[1] || "11x";
// Rewrite the path to include the query string
return `/?${queryString}`;
},
onProxyReq: (proxyReq, req, res) => {
// Add the authorization header
const bearerToken = req.headers['authorization'] || "";
proxyReq.setHeader('Authorization', bearerToken);
},
onProxyRes: (proxyRes, req, res) => {
console.log(`⬅️ Response from Server-3: ${proxyRes.statusCode} for ${req.url}`);
}
}));
< /code>
Я либо получаю 404, а не найдено «не найдено, когда из Application-1 я пытаюсь открыть iframe, чтобы показать приложение-2 < /p>
404
NotFoundError: Not Found
at /Users/abc01/projects/application-2/server/app.js:104:10
Подробнее здесь: https://stackoverflow.com/questions/794 ... ing-iframe
Мобильная версия