簡體   English   中英

node.js中的端口重定向

[英]Port redirection in node.js

我有兩個服務器(在兩個不同的端口上運行),一個用於聊天應用程序,另一個用於API生成服務器(用戶應通過提供公司詳細信息進行注冊,並且我的算法將API密鑰提供給用戶)。

問題是,我正在檢查用戶提供的有效API密鑰,如果API密鑰為true,則應將其重定向到聊天服務器(端口號5200)。

但這是行不通的,請給出任何解決此問題的想法。

這是我的代碼,

`

app.post('/checkAPIkey',function(req,res){
        var apikey=req.query.apikey;

        var apikey1=uuidAPIkey.isAPIKey(apikey);
        if(apikey1){
            res.writeHead(302, {
    Location: 'http://localhost:5200'
});
        }else{
            res.end("error");
        }

});`

您所需要的稱為請求轉發。

例:

const http = require('http');

app.post('/checkAPIkey', function(req,res){
    var apikey=req.query.apikey;

    var apikey1 = uuidAPIkey.isAPIKey(apikey);
    if(apikey1){
        const options = {
            port: NEW_PORT,
            hostname: 'NEW_HOST',
            method: 'POST',
            path: '/'
         };
        var reqForward = http.request(options, (newResponse) => {
                //Do something with your newResponse
                var responseData = "";
                newResponse.on('data', (chunk) => {
                    //Add data response from newResponse
                    responseData += chunk;
                });

                newResponse.on('end', () => {
                    //Nothing more, send it with your original Response
                    response.send(responseData);
                });
        });

        // If ERROR
        reqForward.on('error', (e) => {
             console.error('Error: ' + e);
        });

        // Write to the request
        reqForward.write(YOUR_POST_DATA);
        reqForward.end();
    } else {
        res.end("error");
    }
});

暫無
暫無

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

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