Express.js proxy post request - javascript

I reviewed request module for node https://github.com/mikeal/request
But can't figure out how to proxy POST request to remote server, example
app.post('/items', function(req, res){
var options = {
host: 'https://remotedomain.com',
path: '/api/items/,
port: 80
};
var ret = res;
http.get(options, function(res){
var data = '';
res.on('data', function(chunk){
data += chunk;
});
res.on('end', function(){
var obj = JSON.parse(data);
ret.json({obj: obj});
console.log('end');
});
});
});

Unless I am missing something from your question, you can just do a simple post, and then do something with the response data:
var request = require('request');
app.post('/items', function(req, res){
request.post('https://remotedomain.com/api/items', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the body of the response. If it's not there, check the response obj
//do all your magical stuff here
}
})

Related

How to handle client POST body request flow using Expect: 100-continue header?

I am an impatient learner
I'm looking for information on how to control data flow between client and server in this way:
what I want is, the client sends a POST request, together with an Expect: 100-continue header, then the server processes the headers and validates session information, if everything is ok the server sends the response status code 100 and finally the client sends the body of the request.
my doubts are not about the validation of the headers but about how to regulate the dataflow of the client request POST body to server, if validation result is not the expected reject request and respond client request error status
if is there any way to do this, how to do it correctly?
I don't speak english natively apologies for any mistake
thanks for any help.
Here an example with node 12:
// server.js
const http = require('http')
// This is executed only when the client send a request without the `Expect` header or when we run `server.emit('request', req, res)`
const server = http.createServer((req, res) => {
console.log('Handler')
var received = 0
req.on('data', (chunk) => { received += chunk.length })
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.write('Received ' + received)
res.end()
})
})
// this is emitted whenever the client send the `Expect` header
server.on('checkContinue', (req, res) => {
console.log('checkContinue')
// do validation
if (Math.random() <= 0.4) { // lucky
res.writeHead(400, { 'Content-Type': 'text/plain' })
res.end('oooops')
} else {
res.writeContinue()
server.emit('request', req, res)
}
})
server.listen(3000, '127.0.0.1', () => {
const address = server.address().address
const port = server.address().port
console.log(`Started http://${address}:${port}`)
})
The client
// client.js
var http = require('http')
var options = {
host: 'localhost',
port: 3000,
path: '/',
method: 'POST',
headers: { Expect: '100-continue' }
}
const req = http.request(options, (response) => {
var str = ''
response.on('data', function (chunk) {
str += chunk
})
response.on('end', function () {
console.log('End: ' + str)
})
})
// event received when the server executes `res.writeContinue()`
req.on('continue', function () {
console.log('continue')
req.write('hello'.repeat(10000))
req.end()
})

while sending data through post request using request module in nodejs got error

var http = require('http');
var querystring = require('querystring');
var request = require('request');
var postData = querystring.stringify({
msg: 'hello world'
});
var request = require('req')
var options = {
hostname: 'localhost',
port: 8000,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS:', res.statusCode);
console.log('HEADERS:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('BODY:', chunk);
});
res.on('end', function() {
console.log('No more data in response.');
});
});
when i run this code I am getting cannot find 'req' module .I could see all the modules are properly installed in package.json and i did npm install too.Is there any problem in the code ?
Get rid of this line: var request = require('req')
You need to delete var request = require('req');

Sending JSON response from NodeJS/Express

sorry for the n00b question I have been kinda stuck so I was hoping you guys could put me in the right direction.
I am making an app that is retrieving data by NODEJS from a REST API. (This is a success and works).
I then have a listen URL (my own API) in express that I invoke by going to the browser http://localhost/api or by using POSTMAN. So far so good, I see in the console (NODE Console) that my request gets handled perfectly as I see the JSON response, however, I would also like to see the JSON response in the browser or POSTMAN as JSON Response, not just the console I know I am missing something in my (simple) code but I am just starting out.... Please help me out here is my code.
var express = require("express");
var app = express();
const request = require('request');
const options = {
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
}
};
app.get("/api", function(req, res) {
request(options, function(err, res, body) {
var json = JSON.parse(body);
console.log(json);
});
res.send(request.json)
});
app.listen(3000, function() {
console.log("My API is running...");
});
module.exports = app;
Much appreciated!
To send json response from express server to the frontend use res.json(request.json) instead of res.send(request.json).
app.get("/api", function(req, res) {
request(options, function(err, res, body) {
var json = JSON.parse(body);
console.log(json); // Logging the output within the request function
}); //closing the request function
res.send(request.json) //then returning the response.. The request.json is empty over here
});
Try doing this
app.get("/api", function(req, res) {
request(options, function(err, response, body) {
var json = JSON.parse(body);
console.log(json); // Logging the output within the request function
res.json(request.json) //then returning the response.. The request.json is empty over here
}); //closing the request function
});
Much thanks to ProgXx, turned out I used the same res and response names. Here is the final code. Much thanks ProgXx
var express = require("express");
var app = express();
const request = require('request');
const options = {
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
app.get("/api", function(req, res) {
request(options, function(err, output, body) {
var json = JSON.parse(body);
console.log(json); // Logging the output within the request function
res.json(json) //then returning the response.. The request.json is empty over here
}); //closing the request function
});
app.listen(3000, function() {
console.log("My API is running...");
});
module.exports = app;

How can I make AJAX requests using the Express framework?

I want to send AJAX requests using Express. I am running code that looks like the following:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
// here I would like to make an external
// request to another server
});
app.listen(3000);
How would I do this?
You can use request library
var request = require('request');
request('http://localhost:6000', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the body of response.
}
})
You don't need Express to make an outgoing HTTP request. Use the native module for that:
var http = require('http');
var options = {
host: 'example.com',
port: '80',
path: '/path',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var req = http.request(options, function(res) {
// response is here
});
// write the request parameters
req.write('post=data&is=specified&like=this');
req.end();
Since you are simply making a get request I suggest this
https://nodejs.org/api/http.html#http_http_get_options_callback
var http = require('http');
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
if(res.statusCode == 200) {
console.log("Got value: " + res.statusMessage);
}
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
That code is from that link

In Node.js / Express, how do I "download" a page and gets its HTML?

Inside the code, I want to download "http://www.google.com" and store it in a string.
I know how to do that in urllib in python. But how do you do it in Node.JS + Express?
var util = require("util"),
http = require("http");
var options = {
host: "www.google.com",
port: 80,
path: "/"
};
var content = "";
var req = http.request(options, function(res) {
res.setEncoding("utf8");
res.on("data", function (chunk) {
content += chunk;
});
res.on("end", function () {
util.log(content);
});
});
req.end();
Using node.js you can just use the http.request method
http://nodejs.org/docs/v0.4.7/api/all.html#http.request
This method is built into node you just need to require http.
If you just want to do a GET, then you can use http.get
http://nodejs.org/docs/v0.4.7/api/all.html#http.get
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
(Example from node.js docs)
You could also use mikeal's request module
https://github.com/mikeal/request
Simple short and efficient code :)
var request = require("request");
request(
{ uri: "http://www.sitepoint.com" },
function(error, response, body) {
console.log(body);
}
);
doc link : https://github.com/request/request
Yo can try with axios
var axios = require('axios');
axios.get("http://www.sitepoint.com", {
headers: {
Referer: 'http://www.sitepoint.com',
'X-Requested-With': 'XMLHttpRequest'
}
}).then(function (response) {
console.log(response.data);
});

Categories

Resources