3

I have this simple node.js proxy server implementation:

const s = http.createServer((req, res) => {

  console.log('req method:', req.method);

  if(String(req.method || '').toUpperCase() === 'OPTIONS'){
    res.setHeader('Access-Control-Expose-Headers', '*');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Max-Age', '3600');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Access-Control-Request-Method', 'POST');
    res.setHeader('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
    res.setHeader('Allowed', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
    return res.writeHead(200);
  }

  // ...
});

the problem is that it's not receiving any requests except OPTIONS requests and I suspect that's because it's not handling the OPTIONS requests correctly. I want to allow everything because this is all running locally on localhost - is there something I am doing wrong with my OPTIONS request handling for this proxy server?

When I use the http-proxy lib, everything seems to work fine:

const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({target:'http://localhost:2020'});
const s = http.createServer((req,res) => proxy.web(req,res));

..so there is something wrong with my implementation...I guess the most basic question - as a proxy server should I be forwarding the OPTIONS requests to the proxied server or just be responding early? that's definitely the first decision point..

  • 1
    When using `res.writeHead`, you also need to do a `res.end` to end the connection as far as I recall. At least give it a try :) Docs: https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers – abondoa Mar 11 '20 at 00:02
  • @abondoa yeah that might be part of it for sure –  Mar 11 '20 at 16:52

1 Answers1

1

One thing I noticed, is that you are missing the Content-Length header.

According to RFC7231 section 4.3.7 you must send

Content-Length: 0

if you do not have a response body.

And regarding the 2nd part of your question: OPTIONS requests shall be forwarded to the destination server. They are not cacheable.

Community
  • 1
  • 1
Bernhard
  • 661
  • 4
  • 6
  • so the proxy server should forward the options request to the destination server, instead of responding early to the client? I would have guessed responding early would be perfectly fine. –  Mar 11 '20 at 16:51
  • 1
    According to the RFC, you mustn't respond early. But I guess you can do that nevertheless as performance optimization, if you are sure how your application behaves. – Bernhard Mar 12 '20 at 11:08