reading request object in node.js from localhost - javascript

I'm new to node.js and I'm trying out a few easy examples using localhost:XXXX.
I want to read my request object from node. I have a book and in the book they use cURL(some program) to comunicate with node instead of the browser. Is it possible to write something in the browser adress field and send it to localhost and have a request object sent to node that looks exactly like if I had a typed in a url to a server somewhere? OIf so, how do I write? Do I have to use cURL or something like it if i use localhost?
I'm very new to node and javascript so I dont't know if I'm using the right words. I have tried to search but I dont't think I know the right terms to search for.
This is my server code:
var port = 3000;
http.createServer(function (req, res) {
var url = parse(req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n' + url );
}).listen(port);
When i write http://localhost:3000/hello.com in the address field i was hoping i would get Hello world hello.com in the browser but i get hello world [object object]
Please help.

You can use your regular browser by testing it. In your URL address enter URL address that you have in your cURL address. For instance:
localhost:3000/index.html
If you would like to have more sophisticated tool that gives you more information about request/response you can use tool like Postman for that
In your code use:
res.end('Hello World\n' + url.parse(req.url, true));
url is an object, you need to specify property or method that you are calling on it.
Here is an example on how to parse URL. Easy URL Parsing With Isomorphic JavaScript:

Above answer given by #Vlad Beden looks good but you may want to play with following code
var http = require("http");
var port = 3000;
http.createServer(function (req, res) {
console.log('Requested method: ', req.method);
var params = parseUrl(req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
var data = 'Hello World'
for(var i=0; i<params.length; i++)
data += '\n'+params[i]
res.end(data);
}).listen(port);
var parseUrl = function(url) {
var params = [];
if(url && url != '' && url != '/') {
url = url.replace(/^\/|\/$/g, '');
params = url.split('/');
}
return params;
}
You may try http://localhost:3000/hello.com or http://localhost:3000/hello.com/google.com/more.com/etc . I would like to recommend you print request object console.log(req) and have a look to understand url, method, headers, etc.

Related

Node.js - Window.Location.Href Not Working

I am trying to build a Puppeteer app that can be uploaded to a web server and receive parameters via the URL, but I can't seem find a way to get the current URL from my browser using Node. Right now I have a default server.js file created by Visual Studio which I modified to include code for getting the URL, but when I run the file I get an object promise error for window.location.href.
Here is the codeL
'use strict';
var http = require('http');
var port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
var url = window.location.href;
res.end('Hello World\n' + url);
}).listen(port);
My goal is to be able to get the URL and then pass it to my Puppeteer script as a parameter when it is run. The above code should result in a url value of http://localhost:1337 which could then be modified to include any additional parameters by appending query strings.
Next I tried getting the URL outside of the createServer loop by appending the following:
var url = window.location.href;
document.write(url);
That causes the app to crash with no error message beyond failing to connect to the server.
This is my first Node.js application, so the concept of server side javascript is new to me.

How to handle routes that have # in nodejs with expressjs?

The question is related to: when I refresh the page, not the page loads. Angularjs + Nodejs
But in this case I disable html5mode and , therefore the url the symbol appears #. I want to have control access to certain sections of the code that I show below, but do not know how to handle the #
app.get(['/homepage', '/recoveryPassword', '/manageAccount', '/shop/:itemId/cat/:categoryId', '/shop/:shopName', '/manageMyShops', '/manageMyShops/id/:shopId', '/manageWeb'], isLoggedIn, function (req, res) {
res.end();
});
I am reluctant to post this because I think this is NOT a real solution to OP's problem. To me this is a hack, so use it at your own risk.
To start with - it is unconventional for REST URL to have special characters like '#' in them. While I believe there is no standard way of naming the endpoints but it is recommended to make sure the URLs follow these rules;
all lower-case (because url are not case-sensitive)
no special characters
no camel case
Anyway, my approach is.
On the server code;
Assuming you are defining a path /config# then replace the '#' char with something unique e.g. _bbb Unique enough? you judge, just make sure it doesn't clash with other endpoints.
Add an express layer to decode the URL's special character and replace the special character with the unique word you have given in point 1. (This will be more clear when you see the code).
Client code:
Encode the URL. Why? Because URL can't have '#', because it is a reserved character. So it has to be encoded as '%23' instead.
Example:
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/${encodeURIComponent('config#')}`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.use((req, res, next) => {
let decoded_url = decodeURIComponent(req.url);
req.url = decoded_url.replace('#', '_bbb');
next();
});
app.get('/config_bbb', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}
The idea here is. When the client calls the endpoint, yes the URL is still with /config# but you encode it so that it looks like /config%23.
See:
http://www.w3schools.com/tags/ref_urlencode.asp
Then when the request comes through into the server, the layer you have added in expressJS would decode the URL from /config%23 to /config# and you replace the # char with something unique. Let say _bbb, so that the final URL is /config_bbb which gets routed to the actual endpoint.
Unfortunately express doesn't like endpoints to have special characters in them, if you don't replace the # to be something recognizable then you will find that it doesn't get routed it properly even thou the URL matches.

Making HTTP requests from server side

I have some code that is trying to get a JSON result from the Soundcloud API.
I registered an app, got the client id and such, and I'm trying to make a call like this:
var querystring = require('querystring');
var http = require('http');
var addr = 'http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=XXXXX';
var options = {
hostname: "api.soundcloud.com",
path: "/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=XXXXXx",
method: "GET",
headers: {
"Content-Type": "application/json"
}
}
var request = http.get(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(chunk) {
console.log(chunk);
});
});
This produces a result that looks like this:
{"status":"302 - Found","location":"https://api.soundcloud.com/tracks/49931.json?client_id=xxxx"}
When I use the same URL in Chrome, I get the proper JSON info. How do I properly make this call from server side script?
The built-in http client does not handle redirects. However request does and has many other features the built-in client does not support out of the box.
Today I updated my own NodeJS Api-Wrapper Package for Soundcloud, which can be found here: https://www.npmjs.com/package/soundcloud-nodejs-api-wrapper
It does server side API communication, which includes data modification. No user popup window and redirect url is needed.
I did not found yet any other package having support for this in NodeJS.

responding with a json object in Node js

I want to return a Json object in 200 OK.
I am getting the data from my nosql.
I know the how to fill the structure. (that is in the json body the values to keep)
Here Name, Class and Address are fixed:
Name= entity[4]
Class= entityclass[4]
Address = entityaddrss[4]
...
enity..will be coming from nosql.
how can I construct and send a 200Ok with json body.
response.end({})
can you plesae let me what I should write in end.I have all the required data:
Name= entity[4]
Class= entityclass[4]
Address = entityaddrss[4]
Ok now that you added a few details in your first comment (you should edit the question and add these), I think I can answer what you are after.
var http = require('http')
var port = process.env.PORT || 1337;
var get_nosql_data = function(callback){
// do whatever it is here you need to get the data back
// and format it into a json object. pseudocode follows.
// error handling is also needed here, but not relevant to the answer
var db = require('db');
db.getData('some query', function(res){
var data = { name: res.entity[4], class: res.entityclass[4], address: res.entityaddrss[4] };
callback(data);
});
}
http.createServer(function(req, res) {
get_nosql_data(function(data){
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
}).listen(port);
As long as you sub in the database values for the placeholder strings I have there, you should be up and running. This also should align with what azure already has set up for you.
Related, I would highly recommend checking out express - this will make your life a lot easier writing node web apps.

How to append new line character in node.js?

I'm new to node.js and I'm trying to write a program that receives http requests and forwards the contents through a socket. At the other end of the socket is a paging system that needs messages terminated with a new line character. So far, it works fine, except there is an extra message sent with the contents: undefined.
When I print the contents of the pager message to the client's browser, there does not appear to be a new line. Am I doing this right?
sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
net = require("net");
socket = new net.Socket();
socket.connect(4000, '192.168.0.105');
var httpServer = http.createServer(function(request, response) {
var uri = String(url.parse(request.url).query);
var message = uri.split("=");
var page = 'FPG,101,0,3!A' + message[0] + '\n';
response.writeHead(200, {"Content-Type":"text/html"});
response.write('sending message: ' + page + " to pager");
response.end();
socket.write(page);
}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
EDIT: I narrowed it down further. It turns out that if I do:
var page = 'FPG,101,0,3!A' + 'hello' + '\n';
It works okay. So the output of uri.split("=") must not be what I am expecting.
I'm sure the new line is there, but you aren't going to see it when you send your Content-Type as text/html. In HTML, \n is just other whitespace, and is treated as such. Use text/plain instead.
Since content type is 'text/html',we can happily use break statement.Just like this
res.write('hello'+'<br/>');
res.write('nice to meet you');
You can try this code in node:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('hello,this is saikiran'+'<br/>');
res.end('nice to meet you');
}).listen(process.env.PORT || 8080);
console.log('server running on port 8080');
As per content type of text/plain, you can also use \r to send a return input
to the client's browser
I figured out what the problem was. For some reason the browser was sending an additional request to the page right after my request. I just filtered for requests with a certain format and that fixed it.
Consider using \\n instead of \n for new line.

Categories