PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] How to post data between 2 node js apps o

 April 21, 2022     amazon-ec2, api, connection, express, node.js     No comments   

Issue

On same AWS EC2 instance I run 2 Node.js apps. The first one acts as API gateway (verifies credentials, throttles requests). The second one is responsible for saving info in a database. I need 2 apps because in time they will be 2 separate microservices. For now it is cheaper to host them on the same instance.

I need to forward the POST request from the first app to the second one. One of the fields contains big chunks of HTML and cannot be passed inside a GET request (plus the encoding issues).

First app receives an AJAX POST from browser and forwards the data with request module. I am using the localhost to call for the other service.

router.post('/save', (req, res) => {

    let json_obj = JSON.stringify(req.body)
    let url = "http://127.0.0.1:3000/save"

    request.post({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        url: url,
        form: json_obj
    }, function(error, response, body){
        res.send(body)
    })   
});

Second app listens for data, but req.body is null

router.post('/save', (req, res) => {
    console.log(req.body)

Is it possible to forward data between apps? Or should I have an another approach?


Solution

I had to use body-parser in order to handle the body of the request.

const bodyParser     = require('body-parser')
...

// Configure express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({limit: '3mb', extended: true }))
app.use(bodyParser.json({limit: '3mb'}))


Answered By - Cristi Ghinea
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing