簡體   English   中英

如何使用 Express.js 和 node-fetch 將用戶重定向到自定義 URL 方案?

[英]How can I redirect the user to a custom URL scheme with Express.js and node-fetch?

抱歉,如果我對服務器相關詞語的使用有誤,我是新手。 我有兩個 Express.js 服務器,一個在端口 3000 上,一個在端口 8000 上。瀏覽器在這兩個端口上呈現兩個不同的 HTML 文件。 首先,我在端口 8000 上啟動服務器。一旦在端口 3000 上啟動服務器,我想將在端口 8000 上查看站點的用戶重定向到自定義 URL 方案以打開已安裝的應用程序(使用“example://” ). 此刻我 console.log 在另一台服務器啟動后立即在端口 8000 上“收到”。 如何將用戶重定向到 URL“example://”以便應用程序打開?

這是我的服務器一(端口 3000)的代碼:

import express, { response } from "express";
import fetch from "node-fetch";
import * as path from 'path';
import { fileURLToPath } from "url";


const touchpointApp = express();
const port = 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

touchpointApp.get('/', (req, res) => {
    res.sendFile('/index.html', { root: __dirname });
});

touchpointApp.listen(port, () => {
    console.log('Running on Port 3000');
    fetch("http://192.168.2.127:8000/launch").then(res => {console.log("Success")});
    
})

這是我的服務器二(端口 8000)的代碼:

const { response } = require('express');
const express = require('express');
const open = require('open');
const router = express.Router();
const path = require('path');
const smartMirror = express();


router.get('/', function(req, res){
    res.sendFile(path.join(__dirname + '/index.html'));
});

smartMirror.use('/', router);
smartMirror.listen(process.env.port || 8000);

console.log('Running on Port 8000');


smartMirror.get("/launch", (req, res) => {
    console.log("Received");
    res.status(200);
})

由於之前的測試,該代碼目前是弗蘭肯斯坦的怪物。 我正在使用 NodeJS 來啟動服務器。

這是我對你的意圖的理解:

  1. 用戶在瀏覽器訪問 http://somehost:8000/someUrl 得到一個頁面
  2. 你在端口 3000 上啟動服務器,8000 服務器以某種方式檢測到這個
  3. 對 http://somehost:8000/someUrl 的后續請求現在被重定向到 http://somehost:3000/differentUrl,因此用戶現在正在 3000 服務器中的頁面之間導航。 請注意,8000 服務器告訴瀏覽器:“不要看這里,go 到 3000 服務器尋求答案”。

如果這是您的意圖,那么您可以通過以下方式發送重定向

smartMirror.get("/launch", (req, res) => {
    res.redirect("http://somehost:3000/differentUrl");
})

所以你可能有這樣的代碼

smartMirror.get("/launch", (req, res) => {
    // assuming that you can figure out that the 3000 server is running
    if ( the3000ServerIsRunning ) {
         let originalURL = req.originalUrl;
         
         let redirectedURL = // code here to figure out the new URL
         res.redirect("http://somehost:3000" + redirectedURL);
    else {
          // send a local respons
    }
    
})

我認為您可以使用location http 響應 header 來完成。

res.location('example://...')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM