how to find request parameters in 'nodejs' - node.js

when i sent a request to nodejs server,
how can we find the parameters sent in the request query when request sent to nodejs server.
req.param
req.params
req.query
all giving undefined.
also when i stringify req request it gives error :
Converting circular structure to JSON
How to find query parameters.

You can use the url module:
$ npm install url
And then something like this:
var http = require("http");
var url = require("url");
http.createServer(function(req, res) {
var parsedUrl = url.parse(req.url, true); // true to get query as object
var queryAsObject = parsedUrl.query;
console.log(JSON.stringify(queryAsObject));
res.end(JSON.stringify(queryAsObject));
}).listen(8080);
console.log("Server listening on port 8080");
Test in your browser:
http://localhost:8080/?a=123&b=xxy
For POST requests you can use bodyParser.

Related

Can't fetch the authorization code after the redirect url

I am working on Salesforce and Slack integration. And I don't know much about javascript and its related technologies. Could you please look into the code and let me know whats missing?
// Import express and request moduless
var express = require('express');
var request = require('request');
var url = require('url');
var clientId = '****';
var clientSecret = '****';
var SF_LOGIN_URL = "http://login.salesforce.com";
var SF_CLIENT_ID = "****";
// We define the port we want to listen to. Logically this has to be the same port than we specified on ngrok.
const PORT=4390;
// Instantiates Express and assigns our app variable to it
var app = express();
app.enable('trust proxy');
//var server = http.createServer(app);
//Lets start our server
app.listen(PORT, function () {
//Callback triggered when server is successfully listening.
console.log("Example app listening on port " + PORT);
});
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
// Route the endpoint that our slash command will point to and send back a simple response to indicate that ngrok is working
app.post('/oauth', function(req, res) {
oauth(req, res);
});
function oauth(req, res){
res.redirect(200, `${SF_LOGIN_URL}/services/oauth2/authorize?response_type=code&client_id=${SF_CLIENT_ID}&redirect_uri=****/oauth&display=touch}`);
console.log(url.location.href);
}
It looks to me like you're redirecting an authorization request to Salesforce, and asking Salesforce.com (SFDC) to redirect it back to ****/oauth (from the redirect_uri= query parameter to the SFDC URL.
Are you hoping it will get redirected back to your own /oauth endpoint?
If so, it's possible SFDC is redirecting it with a GET operation rather than a POST operation. Be aware that the parameters to a GET show up in req.params rather than req.body.
Try implementing a get() handler to see if you get something workable.
app.get('/oauth', function(req, res) {
console.log ('GET /oauth', req.params)
/* do something here */
});

NodeJS Request handler

I have some issues with a server that does not support IPv6 requests from Apple Application Review. So they reject my update.
And i'm thinking of making a request handler as a middle server, with nodejs.
So my app will send the requests in my new server, which server will send the request to the old server, take the response json back, and serve it back as well in my app.
So lets say the old webserver request was the following
https://www.example.com/example/api/index.php?action=categories&subaction=getproducts&category_id=100304&limit=0,30
But the request parameters are not always the same!
It may vary but the main URL is always the same
https://www.example.com/example/api/index.php?
The question is how to get the request params dynamically, make a request to the old webserver and return the response to the request of the new webserver?
You just need a very simple proxy like this;
const express = require('express')
const request = require('request')
const app = express()
const BASE_URL = 'http://www.google.com' // change accordingly
app.use('/', (req, res) => {
request({
url: BASE_URL + req.originalUrl
}).pipe(res)
})
app.listen(8900, () => console.log('Listening...'))
req.originalUrl will allow to concatenate the path + the query string to your base url

Capturing GET request params in Node.js

I am trying to capture current GET URL and query params in node.js code. I jut realized windows.loication does not work in node.js as it is for client-based execution only. I have tried multiple things but am not able to capture the GET request. Here is what all I have tried.
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
var request = require('request');
var query = url.parse(request.url,true).query;
getFormattedUrl(req);
function getFormattedUrl(req) {
console.log("req.url: " + req.url);
return url.format({
protocol: req.protocol,
host: req.get('host')
});
}
All of these fail for me, giving the errors like :
2016-12-17T03:32:36.164600+00:00 app[web.1]: ReferenceError: request is not defined
2016-12-17T03:43:46.569603+00:00 app[web.1]: ReferenceError: request is not defined
2016-12-17T03:45:14.509168+00:00 app[web.1]: TypeError: Parameter 'url' must be a string, not undefined
Can someone pls suggest how to cpature the GET params in node.js.
If you are using express 4.x then you want req.query
If you are trying to capture the request that is being made from a NODE JS server to another http/https endpoint for debugging or viewing purposes, this might help
var options2 = {
url: "https://www.google.com",
port: '443',
method: 'GET'
}
request(options2, function(error, response){
console.log(options2);
});
where options2 is the defined URL the node js server is trying to reach
When you console log options2 (a variable name i've used, you can call it anything), it will give you all the information about the HTTPS/HTTP call the server is making.
Sample Express JS 4 Code
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Someting')
console.log(req.query);
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
This will launch a localhost server on port 3000
If you do localhost:3000?q=test you will see
{q: test}
in the console/log.
To fix the problem above, just install request module from the command line first, before using it:
npm install request
Interesting things is that to achieve what you need, you do not need to use request module at all. Just use url module as you did above, pass request object (not a module, but actual calling request), and format it using url.format
const url = require('url')
function getFormattedUrl(req) { return url.format(req.url) }

Forward request object(POST) from express js server to another express js server

I want to forward a post request from an express server(from inside post method) to another express server's post method.
Is there any way to do that?
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var lb = 'http://localhost:8000';
after that inside post,
app.post('/emaillist', function(req, res){
console.log(req.body); // printing params correctly
console.log('redirecting to loadbalancer');
console.log(req.body);
apiProxy.web(req, res, {target: lb});
Here problem is that I can't retrieve request paramaters/body sent, in loadBalancer server. When trying to retrieve a property(e.g. email) out of request loadBalancer,
console.log(req.body.sender);
It says cant read a property of undefined.
My question is how to send request to another noder server from a node server and how to retrieve request parameters out of it at receiving node server

Node JS: Where is my POST data?

I have no lack with sending POST request to node js server. I have a simple request and a simple server.
My server code is:
var http = require('http');
var bodyParser = require('body-parser');
http.createServer(function (req, res) {
console.log(req.body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/')
my client request code is:
var val = JSON.stringify({ city:"SomeCity", name:"MyNameIsHere" });
alert(val);
$.ajax({
url: 'http://127.0.0.1:1337',
type: 'POST',
data: { value: val},
success: function(result) {
alert('the request was successfully sent to the server');}
});
So I suppose to get SomeCity and MyNameIsHere strings in the request body at the node js server, but the req.body field is undefined. Have to say that I open my test.html with request code locally with URL like this:
file:///D:/Projects/test.html
May be Im blind and overseen something trivial, but I have no idea what:)
Have to say that I open my test.html with request code locally with URL like this:
file:///D:/Projects/test.html
You're trying to post cross-domain, which you cannot do in this case. Serve your HTML over HTTP so that you can make a POST. If you use your browser's development tools, you will see that the request will never hit your Node.js server (except for a possible pre-flight request for CORS).
Another problem is that you're not actually using body-parser. If you want the post data, you will have to read from req like a stream.
You are including "body-parser" in var bodyParser = require('body-parser');, but you never actually use it. It won't magically parse the request for you. The default request object does not have a body property... see the documentation.
If you want to use the body-parser module, you should probably use express.js and read the documentation on how to connect it as middleware.
If you want to get the body using the built-in http server, you need to consume the request object first using something like this:
if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
if (body.length > 1000000) {
req.connection.destroy();
}
});
req.on('end', function () {
console.log(req.body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
}
Adding express library and bodyparser as middleware did the trick. However I could use the code from neelsg answer but working with built-in http server and handling Post data by my own is too burdensome.
So piece of my working code is here:
var express = require('express');
var http = require('http');
var url = require('url');
var bodyParser = require('body-parser');
var app = express();
app.use(express.bodyParser(
{
keepExtensions: true,
limit: 30*1024*1024 // lets handle big data
}
));
app.use(bodyParser.urlencoded());
Bodyparser by default can handle only 100Kb data in the post request, so I had to increase limit using its config options.

Resources