Target server not recieving the request body in http-proxy? - node.js

I am trying to introduce gateway for my micro services. I got stuck in post method. Target server not receiving the request body. Not sure what i am doing wrong. Can any one help me out. Here is the code
const express = require('express');
const app = express();
const httpProxy = require('http-proxy');
const apiProxy = httpProxy.createProxyServer();
const server1 = 'http://localhost:4000',
server2 = 'http://localhost:4001';
apiProxy.on('proxyReq', (proxyReq, req) => {
console.log(' in proxy req ...');
if (req.body) {
const bodyData = JSON.stringify(req.body);
// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
// stream the content
proxyReq.write(bodyData);
apiProxy.web(req,res, {target: server2});
}
});
app.all('/service1/*', (req,res) => {
console.log("redirecting to server1 ...");
apiProxy.web(req,res, {target: server1});
})
app.all('/service2/*', (req,res) => {
console.log(" req, body : ", req.body);
apiProxy.web(req,res, {target: server2});
})
apiProxy.on('error', (err,req,res) => {
console.log('got an error : ',err)
});
apiProxy.on('proxyRes', (proxyRes,req,res) => {
console.log(' got a response from the server ..');
return proxyRes;
})
app.listen(3000, () => console.log(' proxy running on 3000'));
By using the body parser i am able to print request body but not getting the request body on the target server.
const app = express();
const httpProxy = require('http-proxy');
const apiProxy = httpProxy.createProxyServer();
const server1 = 'http://localhost:4000',
server2 = 'http://localhost:4001';
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.all('/service1/*', (req,res) => {
console.log("redirecting to server1 ...");
apiProxy.web(req,res, {target: server1});
})
app.all('/service2/*', (req,res) => {
console.log(" req, body : ", req.body);
apiProxy.web(req,res, {target: server2});
})
apiProxy.on('error', (err,req,res) => {
console.log('got an error : ',err)
});
apiProxy.on('proxyRes', (proxyRes,req,res) => {
console.log(' got a response from the server ..');
return proxyRes;
})
app.listen(3000, () => console.log(' proxy running on 3000'));

Related

Save JSON file to local folder on client with Nextjs/ NodeJs and Firebase hosting/functions

I'm using NextJS for my application and i would like to write an JSON-file to the client in a function. On my localhost everything works fine and without any problem, but the application gets build and deployed to firebase it isn't working anymore.
I already tried multiple things, i already created the function in the api folder of NextJs and also created an localhost node server and call them in nextjs API as:
var fs = require('fs').promises;
export default function (req, res) {
console.log(JSON.stringify(req.body))
let Data= JSON.stringify(req.body)
fetch('http://localhost:9091/data', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: Data
})
.then((response) => {
console.log('here')
return response.json(); // or .text() or .blob() ...
})
.then((text) => {
console.log(text)
res.status(200)
// text is the response body
})
.catch((e) => {
// error in e.message
});
As said this works when the application runs on localhost but not on firebase hosting/functions.
The node server looks like:
var express = require('express');
var app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
var fs = require('fs').promises;
app.get('/', function (req, res) {
res.send('Hello World');
})
app.post('/data', function (req, res) {
res.send('Hello World');
let Order = req.body;
console.log(Order)
fs.readFile("object.json",'utf8').then(data =>{
let json = JSON.parse(data);
json.push(Order);
fs.writeFile("object.json", JSON.stringify(json)).then( () => { console.log('Append Success'); })
.catch(err => { console.log("Append Failed: " + err);});
})
})
var server = app.listen(9091, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
What I'm trying to achieve is that data is appended to the JSON file and stored locally on the client.
Does anyone have an idea how to handle this properly?

express server returns 405 on routes in production

Im building an express instance for the first time and ive run into an issue where everything works locally, but when deployed sending a post request to the route responds:
Failed to load resource: the server responded with a status of 405
(Not Allowed)
Ive included the relevant code below:
server/index.js
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
const routes = require('./routes')(express)
require('./db')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(process.env.PORT || 8080);
app.use('/', routes);
routes/index.js
var mongoose = require("mongoose");
const randomId = require('random-id');
const Submissions = require('../api/Submissions')
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
router.route('/submission')
.post((req, res) => {
let newSubmission = new Submissions(req.body);
newSubmission._id = randomId(17, 'aA0');
// Save the new model instance, passing a callback
newSubmission.save(function(err,response) {
if (err) {
console.log(err)
} else {
res.setHeader('Content-Type', 'application/json');
res.json({'success':true})
}
// saved!
})
});
return router;
}
client.js
let submission = {
name: this.state.newSubmission.name.trim(),
body: this.state.newSubmission.body.trim(),
email: this.state.newSubmission.email.trim(),
};
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(submission),
};
fetch("/submission", requestOptions)
.then((response) =>
response.json().then((data) => ({
data: data,
status: response.status,
}))
)
.then((res) => {
if (!res.data.success) {
notifier.warning('Failed to submit');
} else {
notifier.success('Submission successful');
}
});

How to Make API calls in express server

I am trying to make a get request in an express server, currently the server simply prints all post requests and it works fine up to that, the issue is when GET request is made the response is returned as 'undefined'
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(port, hostname, () =>
console.log(`Server running at http://${hostname}:${port}/`)
);
Use Postman to send Api calls to the server. I am attaching the link down below.
Install Postman chrome extension, if you're using chrome.
Use the Localhost:port server and post method and add variable to post your query
Hope this helps.
Moreover, Just add this tweak in your code and listen on a proper localhost,
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(1337, function(){
console.log('Express listening on port', this.address().port);
});
Executed the below code
axios .get("https://reqres.in/api/products/3")
.then(response => { console.log(response); })
.catch(error => { console.log(error.response); })
Its executed and working fine.
My Guess is that in your case its going to catch block
Change the following line
.catch(error => {
console.log(error.response);
});
TO
.catch(error => {
console.log(error);
});
And see whether some error is printing.No response object is assigned to error, that may be u r receiving undefined

Node JS header problems with ionic

So i am using ionic framwork to make my app and using nodeJS as my backend but i am still a noob in this and i can't seem to figure it out still after 4 days so hopefully someone could answer this problem to me and why would be appreciated.
So for my ionic client side i do this to make a http.post request
progress() {
var headers = new HttpHeaders();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
let options = {headers: headers};
let postData = {
username: this.username,
email: this.email,
password1: this.password1,
password2: this.password2
};
this.http.post('localhost:4000/api/users', postData, options,).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
});
}
and this is what i am doing to get the data from the server but that's not working
// Packages
let express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
app.use(cors({origin: 'http://localhost:8100'}));
const port = 4000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Whenever you enter localhost:4000/ //
app.get('/', function (req, res) {
res.send(('Server runs'));
});
app.listen(port, () => console.log(`app listening on port ${port}!`));
app.get('/api/users', (req, res) => {
res.send('api/users page');
request.get({
uri: 'http://localhost:8100/create-account'
}, function (err, res, body) {
console.log('error:', err); // Print the error if one occurred and handle it
console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
res.send(body);
});
});
i also tried 'http://localhost:8100' & 'localhost:8100'
so someone help me
You need to add a handler for your POST request. To do this use app.post, and it looks like this
app.post('/api/users', (req, res) => {
// You can find your data here
const data = req.body;
console.log(data);
// Send back a response
res.sendStatus(200);
});

Receiving POST request data using Superagent and Express 4

Express -v : 4.13.3
Superagent -v : 1.4
function to send the POST request from the front-end of my app:
search: () => {
request.post('/api/search')
.set('Content-Type', 'application/json')
.send({hello: 'hello w'})
.end((err, response) => {
if (err) return console.error(err);
serveractions.receiveTest(response);
});
}
my express router file:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({extended: false}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
The request is successfully being sent and received by the router, but req.body is always empty even though I am doing .send({hello: 'hello w'}) with Superagent. What do I need to change in order to correctly send the json object and receive it in my router?
I figured out the answer:
I changed my router file to:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
console.log(req.body);
res.json({test: 'post received'});
});
module.exports = router;
And my request method to:
searchRequest : (data) => {
request
.post('/api/search')
.send({ searchTerm : data })
.end((err, res) => {
if (err) console.log(err);
console.log(res);
})
}

Resources