Reputation: 1407
I want to do something like this but this is throwing an error and I can't seem to use JSON.stringify either. Is there a way to do this?
var http = require('http')
http.createServer(function(req, res) {
res.end(req);
}).listen(3000);
Upvotes: 0
Views: 1447
Reputation: 146134
Start with something simple like this:
var http = require('http');
http.createServer(function(req, res) {
res.write(req.url);
res.end();
}).listen(3000);
If you want to echo back the request, you need to think about what parts of it. HTTP requests have a header and a body. The header is already available when the handler function is called, but the body is a stream that you need to read chunk by chunk, and you can then decide to stream it straight back, parse it, transform it, or whatever. There are lots of examples out there to get started.
Here's a piped version.
var http = require('http');
http.createServer(function(req, res) {
req.pipe(res);
}).listen(3000);
And I test it like so:
curl -X POST -d 'foo=bar' localhost:3000/hello/foo
foo=bar%
This version gives me some valid output put it's not in JSON format. As you can see, the req
object has tons of internal state having to do with server side programming that is unrelated to the content of the incoming HTTP request. Thus it's not the right way to get at the request DATA, which is not the same as the req
object programming interface.
var util = require('util');
var http = require('http');
http.createServer(function(req, res) {
res.write(util.inspect(req));
res.end();
}).listen(3000);
{ _readableState:
{ highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
....etc
Here's a version that sends the request headers back as JSON:
var http = require('http');
http.createServer(function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify(req.headers));
res.end();
}).listen(3000);
And the response:
curl -v localhost:3000
* Adding handle: conn: 0x7fd983804000
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fd983804000) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 3000 (#0)
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:3000
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Fri, 30 May 2014 00:10:02 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
{"user-agent":"curl/7.30.0","host":"localhost:3000","accept":"*/*"}%
Upvotes: 4