Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Send GET request via unix socket

I am new to the node.js. I am trying to setup the client server connection using unix socket, where my client request would be in node.js and server running in the background would be in go.

Client side Code:

    var request = require('request');

    request('http://unix:/tmp/static0.sock:/volumes/list', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body)
        } else {
            console.log("In else part of the receiver" + response.statusCode + body)
        }
    }


})

When I try to communicate with the server written in go it is shows the HTTP error: 400 Bad Request: malformed Host header'

The same works with:

curl -X GET --unix-socket /tmp/static0.sock http://:/volumes/list

Not sure what is wrong with my request. Do we need to send the headers? I expecting the JSON response.

like image 284
Nikita Kodkani Avatar asked Dec 16 '16 04:12

Nikita Kodkani


People also ask

How do I use a domain socket in UNIX?

To create a UNIX domain socket, use the socket function and specify AF_UNIX as the domain for the socket. The z/TPF system supports a maximum number of 16,383 active UNIX domain sockets at any time. After a UNIX domain socket is created, you must bind the socket to a unique file path by using the bind function.

How does socket work in UNIX?

Unix sockets are bidirectional. This means that every side can perform both read and write operations. While, FIFOs are unidirectional: it has a writer peer and a reader peer. Unix sockets create less overhead and communication is faster, than by localhost IP sockets.

How do I handle GET and POST request in node js?

POST request (web browser) var http = new XMLHttpRequest(); var params = "text=stuff"; http. open("POST", "http://someurl.net:8080", true); http. setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http. setRequestHeader("Content-length", params.


1 Answers

To accomplish this without using the request module, try the following:

const http = require('http');

const options = {
  socketPath: '/tmp/static0.sock',
  path: '/volumes/list',
};

const callback = res => {
  console.log(`STATUS: ${res.statusCode}`);
  res.setEncoding('utf8');
  res.on('data', data => console.log(data));
  res.on('error', data => console.error(data));
};

const clientRequest = http.request(options, callback);
clientRequest.end();
like image 129
Geige V Avatar answered Oct 20 '22 01:10

Geige V