简体   繁体   中英

reading request object in node.js from localhost

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM