从一个节点js发送数据到另一个节点js,并在另一节点js上显示发送的数据

时间:2018-07-06 05:44:46

标签: node.js http ejs

我正在尝试将数据从一个节点js服务器发送到另一节点并显示发送的信息。服务器A和服务器B的示例。服务器A向服务器B和服务器B发送的数据将显示服务器A发送的信息以及响应并返回给服务器A。基本上,我的程序类似于付款页面和银行服务器页面。将付款详细信息发送到银行服务器,如果银行服务器单击接受,它将发送回付款页面并继续进行交易。

这是我的付款页面代码:

var postData = JSON.stringify({ user: cardDetails });

    const options = {
        hostname: 'localhost',
        port: 3001,
        path: '/bank',
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'accept': 'application/json'
        }
    };

    const httpreq = http.request(options, (res) => {
        res.setEncoding('utf8');
        res.on('data', (chuck) => {
            console.log(`BODY: ${chuck}`);
        });
        res.on('end', () => {
            console.log('No more data in response.');
        });
    });

    httpreq.on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
    })

    //write data to request body
    httpreq.write(postData);
    httpreq.end();

这是我在银行服务器端的代码: App.js

var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
var serverPort = 3000;
var httpServer = require('http').Server(app);

// ejs template path
app.set("views", path.join(__dirname, "server/views/pages"));
// view engine setup
app.set("view engine", "ejs");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//import order tracking
var bank = require('./server/controllers/bank');

app.get("/bank-server", bank.bankSystem);
app.post("/bank", bank.add);

console.log("Connected!")
app.listen(3001);

这是我的bank.js代码:

exports.add = function (req, res){
    console.log(req.body.user.cardName);
    res.sendStatus(200);

};

exports.bankSystem = function (req, res){
    console.log("Bank Page Working!")
        res.render('bankServer', {
            name: "empty"
        })
    }

最后我的bankServer.ejs代码:

<h1>Connection Worked!</h1>
<p>Card Name is <%= name %></p>

This is the output from payment node js. CardName entered = raysonkira1 This is the output from bankserver node js. received cardName

1 个答案:

答案 0 :(得分:0)

在Bank.js中,您只是发送状态而不是响应。

exports.add = function (req, res){
    console.log(req.body.user.cardName);
    res.sendStatus(200);
    // send the response data here, for example
    res.send("Hello from the bank!");
};

reference