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
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.
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.
I find an easy way to post static
app.use(staticPath, function(req, res, next){
if ('POST' != req.method){
next()
}else{
req.method = 'GET'
next()
}
})
app.use(staticPath, express.static('./static'))
It works well, haha
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.