How get string pathname ?
var http=require('http');
var url = require("url");
http.createServer(function(req,res){
var pathname = url.parse(req.url).pathname;
console.log("Request for " + pathname + " received.");
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello\n');
}).listen(8124,'127.0.0.1');
console.log('Server me!');
There is no error output,but not displayed Request for ....
This seems to work for me:
FL261:~ jvah$ node pathname
Server me!
Request for / received.
And at the same time in the other window using curl:
FL261:~ jvah$ curl http://127.0.0.1:8124/
Hello
Related
I a m kinda stuck. I made a request to a server. I want the server to computer a operation for me, and send me back the result.
Request :
ar http = require('http');
http.createServer(function(req, res){
var response = "Hello from " + req.client.remoteAddress + ":" + req.client.remotePort + "\n to " + req.client.localAddress + ":" + req.client.localPort;
console.log(response);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const Http = new XMLHttpRequest();
console.log("start");
n = 15;
const urlfibo='http://172.22.0.4:8899';
Http.open("POST", urlfibo,false);
var params = 'value=15';
Http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Http.send(params);
console.log(Http.responseText);
response += Http.responseText;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(response);
res.end();
On my server, i don't know where to find the parameter i passed. I've tryed the solution in the doc, but my code is never running into it :
```
response += "\n ON" + req.on
let body = [];
req.on('data', (chunk) => {
response += "bla"
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
My question is : on y server (second part of code), how do i get my params i passed when i sent the request ? I want to do it with nodejs without using frameworks
Thank you
chunk will have all informations because is an object, you just have to assign this values for a new object and look for the parameters. Bug make sure to have in your code:
const bodyParser = require('body-parser');
app.use(bodyParser);
I'm creating HTTP server and inside i'm sending a request to to yahoo finance website and getting some data from it, what i want to do is to print to browser the data i got from yahoo finance.
the thing is that response.write isn't working inside the request.
Here is my code:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');
var host = "127.0.0.1";
var port = 1400;
var server = http.createServer(function (req, res) {
//writing the headers of our response
res.writeHead(200, {'Content-Type':'text/plain'});
// Variable Deceleration
// TODO: move from the global scope
var ticker = "IBM";
var yUrl = "http://finance.yahoo.com/q/ks?s=" + ticker;
var keyStr = new Array();
//
// The main call to fetch the data, parse it and work on it.
//
request(yUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
// the keys - We get them from a certain class attribute
var span = $('.time_rtq_ticker>span');
stockValue = $(span).text();
res.write("trying to print something");
console.log("Stock - " + ticker + " --> text " + stockValue );
}
}); // -- end of request --
res.write('Welcome to StockWach\n');
//printing out back to the client the last line
res.end('end of demo');
});
server.listen(port, host, function () {
console.log("Listening : " + host +":" + port);
});
You have to end the response (res.end();). Almost all browsers buffer some number of bytes from the response before showing anything, so you won't see the trying to print something until the response has ended.
If you use something like cURL though, you will see the trying to print something right away before the response is ended.
I have the following client side javascript code.
<html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function() {
//var parameters = "a=" + JSON.stringify({ Code: "xyyyzz"});
var parameters = "a=" + JSON.stringify({ Code: "x#yyy#zz"});
alert(parameters);
$.getJSON('http://localhost:8080', parameters)
.done(function(str){
alert("success");
})
.fail(function(e) {
alert("failure");
});
});
</script>
</html>
and the following server side node.js code
var http = require('http');
var URL = require('url');
var queryString = require( "querystring" );
handler = function(req, res) {
url = URL.parse(req.url);
var queryObj = queryString.parse( url.query );
var obj = JSON.parse( queryObj.a );
console.log( obj.Code);
};
host = '127.0.0.1';
port = 8080;
http.createServer(handler).listen(port, host);
console.log('Server running at http://' + host + ':' + port + '/');
Now, if I load the .html file, the JSON call is made from the javascript. However, the parameter is not passed in full. It is passed only until the first # character and so causes the nodejs server to crash on the parse function. Now if I uncomment the previous line in the .js where a string without the # is passed, the nodejs server can succesfully parse the parameters.
So my question is, Is JSON incapable of encoding special characters like # in a string ? Or is this a bug ? Or do I need to add anything else to fix this so that x#yyy#zz is passed as a whole string to the nodejs server ?
Your data needs to be url encoded, # has a special meaning in urls.
If you pass an object to $.getJSON it will be automatically encoded for you
var parameters = {"a" : JSON.stringify({ Code: "x#yyy#zz"})};
or you could manually encode it
var parameters = "a=" + encodeURIComponent(JSON.stringify({ Code: "x#yyy#zz"}));
I have a basic node.js setup, but I think I'm missing something.
My main.js:
var a = require('./another.js');
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200,
{
'Content-Type': 'text/html'
});
response.write(a.saysomething('Hi there!') + '<br />');
response.end();
}).listen(27182);
console.log('Server running at http://127.0.0.1:27182/');
My another.js:
exports.saysomething = function (str) {
console.log('in saysomething!');
return str + ' hey there!';
}
The issue is that my console is outputting in saysomething! twice. Am I missing something? When I refresh the page, I expect only one in saysomething!.
Your browser is likely trying to get favicon.ico in addition to the url you are hitting. Try to just do the command on the command line: curl http://127.0.0.1:27182/
Also, you can add logging for request.url. That will show you which urls are being requested.
Here's another way to understand the problem. This node server will track all the requests and show them to you on the browser in JSON. Then you can hit F5 and watch the requests you are making.
var http = require("http");
var messages = [];
http.createServer(function(request, response) {
console.log("We got a hit # " + new Date());
messages.push(request.url);
messages.push(request.headers);
response.writeHead(200, {"Content-Type": "text/plain"});
for ( var i = 0; i < messages.length; ++i ) {
response.write("\n\n" + JSON.stringify(messages[i]));
}
response.end();
}).listen(8888);
PS: See also this duplicate for more info nodejs - http.createServer seems to call twice
In rails I do a POST request to my server:
response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole")
result = JSON.parse(response.body)
In the Node.js app, I want to read From and To:
app.post '/request', (req,res) ->
console.log "I have received a request, sweet!!"
sys.log req.params.from
#sys.log "From: " + req.from + ", To: " + req.to + ", Id: " + req.id
How do I do it?
Thanks
The answer is:
Checks query string params (req.query), ex: ?id=12
Something like this:
var http = require('http'), url = require('url');
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
var _url = url.parse(request.url, true);
response.write("Hello " + _url.query["from"] + "!\n"); // etc: _url.query["to"]...
response.close();
}).listen(8000);
url.parse is a key point... Or you can use querystring.parse(urlString)
You can read more at http://nodejs.org docs section.