POST to NGINX proxy_pass works but I'm getting a 502 Bad Gateway on the client

Viewed 23

what I'd like to achieve is the following:

client -> nginx proxy -> db server -> give response to client

This is what my nginx config looks like:

    server_name {site}.dev www.{site}.dev;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }

    location /api {
            proxy_pass http://localhost:3000/api;
            # proxy_set_header Host $host;
    }

This is what the express server on that server (nginxserver:3000) looks like:

import fetch from "node-fetch";
import express from 'express';
import bodyParser from 'body-parser';

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

var port = 3000;
const databaseServer = 'http://{ip}:3000/';
app.get('/', function(req,res) {
 res.render('index', { title: 'Express' });
})
app.post('/api', function(req, res) {
   console.log('receiving data ...');
   console.log('body is ',req.body);
 
 fetch(databaseServer, { 
   method: 'POST',
   headers: {
     'Accept': 'application/json',
     'Content-Type': 'application/json'
   },
   body: req
 }).then(async (response) => {
   const data = await response.json();
   console.log('Data from DB Listener: ', data)
   res.send(data);
 }).catch((error) => {
   console.error(error);
     res.send('Error: ', error)
 })
});

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

For more context, from http://localhost:3000/api I am making a call to an express server on the database server that then makes the database request.

Now, I'm seeing on both nginxserver:3000 and dbserver:3000 that the requests are being received, yet I get a 502 bad gateway response on the client.

I'd like to be able to get the response from the database server on the client.

Edit: It seems to only happen if I have the Content-Type or body headers set

I'd appreciate any help, thank you !

0 Answers
Related