Capturing GET request params in Node.js - 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) }

Related

Openui5 jquery POST to Node.js Server contains empty request body on server side

I am setting up a sample App using Openui5 as frontend framework, Node.js & Express.js for backend API and MongoDB as database.
My JQuery Ajax post does not contain any body data when arriving at the backend.
I tried several of the solutions provided on stackoverflow, but none of them seems to work for me. MongoDB and Backend Server are running. Data fetching is also working with ui5 data binding to XML View.
controller.js:
onSave: function () {
//get user input from local json model
var oNewEmployee = this.getView().getModel("newEmp").getProperty("/newEmp"),
data = JSON.stringify(oNewEmployee),
url = 'http://localhost:3000/employee';
//do the post
$.ajax({
url : url,
dataType : 'json',
contentType : 'application/json',
data: data,
type : 'POST',
success: function(response){
console.log(response);
}
});
},
server.js:
var express = require("express");
var app = express();
var mongoose = require("mongoose");
var cors = require("cors");
app.use(cors());
mongoose.connect("mongodb://localhost/schichtplaner", { useNewUrlParser: true });
app.post("/employee", function (req, res) {
console.log(req.body);
});
app.listen(3000);
I keep getting undefined as output from console. Would be great if someone has an idea how to solve this.
You should use the body-parser npm module in order to read the POST request payload.
https://www.npmjs.com/package/body-parser

Send array from node.js and use client side

Im a beginner with node.js so bear with me please :D
Simple task: I use express and I want to send an array, lets say ["item1", "item2"] from a node server to a client that calls the server with a get method. When I tried this, I stumbled upon the CORS error.
I also thought about doing a this through a post:
-client:
$(document).ready(function () {
$(".testButton").click(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:3000/test_post",
type: "post",
data: "sent",
success: function () {}
});
});
-server:
app.post('/Quiz_post', function (req, res) {
res.send(["item1", "item2"]);
});
But this also doesnt work. Now I am trying to use cross-fetch client side. Could you please guide me a bit? Thanks!
Add this code in ur app.js to enable CORS.
npm i cors in the project 1st
var cors = require('cors');
var app= express(); //After this line of code add the code below
app.use(cors());

Getting connect ECONNREFUSED 127.0.0.1:80 when attempting HTTP request

I am attempting to make a http request to news.google.com using the native node.js http module. I am getting the connect ECONNREFUSED 127.0.0.1:80 error when I tried the following
var http = require('http');
var payload = JSON.stringify({
name: 'John Smith',
email: 'john.smith#smith.com',
resume: 'https://drive.google.com/open?id=asgsaegsehsehseh'
});
var options = {
hostname: 'https://news.google.com',
path: '/',
method: 'GET'
};
var httpRequest = http.request(options, function(request, response) {
console.log('STATUS', response.statusCode);
response.setEncoding('utf8');
response.on('data', function(chunk) {
console.log('BODY:', chunk);
});
response.on('end', function() {
console.log('No more data in response');
});
});
httpRequest.on('error', function(e) {
console.log('Error with the request:', e.message);
});
httpRequest.write(payload);
httpRequest.end();
Why am I getting this error?
I tried using the request npm module. And it worked!
In my case, issue was actually default behaviour of HTTP client that I was using, axios.
By default, axios redirects us to 127.0.0.1:80 if it doesn't find requested URL or http method(GET/POST/PUT). So better check your URL if are also using axios.
My problem was while using supertest and jest. My mistake was not putting "/" as a prefix to some url. So, double check if the url for the request you are making is proper.
I'm using axios and this error occurred with get request, solved it by adding http:// before my URL (in my case the server is http)
There are several issues here:
The hostname field of the options structure should be just the host, not a URL. In your case it should just be 'news.google.com'.
The signature for the callback to the request method is function (response) -- yours is function (request, response). Lose the first parameter.
As written this will aways return an HTTP redirection to the https site. Replace var http = require('http'); with var https = require('https'); and then use https everywhere instead of http.
I encountered this issue while using supertest and jest. I made the mistake of using ./users instead of /users as the url.
I had the same problem with jest and supertest. Just changed api/blogs to /api/blogs and it worked !
I had the same problem.
Solve it by fixing the HTTP request path mistake in my code.
I had this problem, and my solution (That might not be the same for most people) was that the server was not listening yet, I had to call the axios function after.
store the root url in some variable or environtment and append it before request
so instead of
axios.get('/api/myurl')
do something like
let baseUrl = 'https://google.com"
axios.get(baseUrl + '/api/myurl')
Another cause for this error could be that in your code, you might be referring to an environment variable as:
const localhostUrl = process.env.LOCALHOST_URL;
Whilst, not having this variable defined, (as expected), in your .env file as:
LOCALHOST_URL = http://localhost:8000/

How to proxy to root path with node http-proxy

I am trying to setup a proxy with an express app to a root path from a specific path in my application:
http://my-domain.com/some/route --> http://another-domain:8000/
I have tried multiple things per the http-proxy docs but I keep hitting a wall with the paths/routing. I am trying to do this within a logged in express app so that I can utilize my authentication behind the app i'm trying to proxy too. I keep getting an error with the proxy'd app saying the path '/some/route' is not defined...etc.
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
proxy.proxyRequest(req, res, {
host:'localhost',
port:8000
});
I've also tried:
var url = 'http://localhost:8000/';
var httpProxy = require('http-proxy'),
proxy = httpProxy.createProxyServer({});
proxy.web(req,res, { target: url }, function(e) {
console.log('proxy.web callback');
console.log(e);
});
The function calls but I end up with an express 404 error...
I would also like to pass in some variables if that is possible so for example:
http://my-domain.com/some/route?var1=something&var2=something --> http://another-domain:8000/?var1=something&var2=something
But could not figure out if that was possible, I tried setting it on the request since that was being sent into the proxyRequest, but was unable to find them in the second application.
No, you can't do this with just node-http-proxy.
But it's possible with http-proxy-middleware (and you likely use it already):
From comment by #chimurai on github:
You can rewrite paths with the pathRewrite option.
var options = {
target: 'http://test.com',
changeOrigin: true,
pathRewrite: {'^/api' : ''} // <-- this will remove the /api prefix
};
server.middleware = proxyMiddleware('/api', options);
And if you come here because you're using webpack-dev-server, note that it also internally uses http-proxy-middleware, starting from version 2.0.0-beta (see PR).
Side note: There is also a node-proxy plugin, http-proxy-rules, so you can use this one if you don't want middleware.
Well, I encounter another problem, but needed to solve this problem first. I came up with this code, which worked fine for me ;)
Just use this for "/some/route"
.... // your stuff
httpProxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('some error');
});
app.all( '/some/route/*' , function( req , res ) {
var url = req.url;
url = url.slice(11); // to remove "/some/route"
req.url = url;
return httpProxy.web(req, res , { target: "http://another-domain:8000" } );
} );
hope this helps.

how to find request parameters in 'nodejs'

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.

Resources