G
G
Gios2014-11-16 00:38:31
Node.js
Gios, 2014-11-16 00:38:31

GET Request Nodejs without Express?

How to make a GET Request without using Express.js. In Express, for example, it is written:
app.get("/read", function(req, res) {
// Here's what to do
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2014-11-16
@MarcusAurelius

var http = require('http');
http.createServer(function (req, res) {
  if (req.method === 'GET' && req.url === '/read') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World');
  } else res.end('You should open /read');
}).listen(81);

But this is how many if-s will be written this way. If you don't like express, try impress. There, the same handler can be made simpler, create the /read folder and put html.template in it with the necessary HTML and no code, and the API method: /api/method.json called via POST: make the file /api/method.json/ post.js (or any other HTTP method delete.js, get.js...) and in it:
module.exports = function(client, callback) {
    dbImpress.users.find({ group: client.fields.group }).toArray(function(err, nodes) {
        callback(nodes);
    });
}

Result:
[
    { "login": "Vasia Pupkin", "password": "whoami", "group": "users" },
    { "login": "Marcus Aurelius", "password": "tomyself", "group": "users" }
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question