开发者

Node.js: Create a Web Hook

What's the easiest way of cr开发者_开发知识库eating a Web Hook in Node.js? (POST to a URL).

Thanks


var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: ...
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

From the http.request docs.

Basically you can request with an opinions hash to a host/port + path with a method. Then handle the response from that server.


From the Node.js homepage:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

You can access the req object to get at the data.

For a more high level approach, check out express.js.

You can do things like:

var app = express.createServer();

app.post('/', function(req, res){
    res.send('Hello World');
});

app.listen(3000);


I highly recommend the node.js module restler.

rest.post('http://user:pass@service.com/action', {
    data: { id: 334 },
}).on('complete', function(data, response) {
    if (response.statusCode == 201) {
        // you can get at the raw response like this...
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜