Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to GET/POST files in express.static()

I'm a little confused as to how Express serves files.

Currently I have a /public directory to hold client-side resources. I configure Express using

app.use(express.static(__dirname + '/public'));

It was my impression that anything in this directory was public, and that HTTP method urls defaulted /public as the root directory for access (unless otherwise routed manually by Express).

There is no problem using GET on any file in this directory (client-side scripts, images, ect. However, I get 404's when trying to POST files inside this directory. Do I need to manually route all POST requests ala

app.post(route, callback)

Thanks for you help

like image 659
Colin Avatar asked Jan 12 '23 14:01

Colin


2 Answers

Connect, and therefore, Express, the static middleware only accepts GET requests. See here.

If you are trying to overwrite files in the public with a POST, you'll want to create a separate route for that.

like image 71
fakewaffle Avatar answered Jan 16 '23 22:01

fakewaffle


Connect/Express' static middleware only supports GET and HEAD method:

if ('GET' != req.method && 'HEAD' != req.method) return next();

So, yes, if you want to be able to POST to paths matching static files, you'll need to define the handler(s) yourself.

like image 36
Jonathan Lonowski Avatar answered Jan 16 '23 21:01

Jonathan Lonowski