expressjs / serve-static

Serve static files
MIT License
1.39k stars 228 forks source link

Add allowPost option #73

Closed purplestone closed 7 years ago

purplestone commented 8 years ago

Use serve-static as mock server for ajax development. need POST request .json files.

dougwilson commented 8 years ago

Hi @purplestone, I'm not sure I understand the use-case still. Can you provide some example code someone would write if they were going to use this feature? I'm trying to understand anything added, as I'll end up needing to support the code, answer user questions about it, and be able to triage changes against the feature. I hope that makes sense about why I need to better understand the purpose of the feature, which does not seem very clear at this point.

purplestone commented 8 years ago

Now I'm debugging the frontend code:

$('button').on('click', function () {
        $.post('/addUser.do', oData, function () {showSomeThing()});
});

Local development I mock the /addUser.do response at http.createServer(serveStatic('mockData/')).listen(80) File mockData/addUser.do

{
    "action" : "ok"
}

Then online server will app.use('/addUser.do', function () {addUserToDB()});

dougwilson commented 8 years ago

Hi @purplestone, thanks for sharing how you are trying to use this module! So as I was hinting to you in the other issue, I think you may be better off using the send module directly, given your code example.

Your code example: http.createServer(serveStatic('mockData/')).listen(80)

This example even without this PR has a few issues, namely that you cannot use a middleware as the request listener for the Node.js HTTP server, as there are many conditions that will either cause a crash or hang.

Would you be willing to give the following code a try? It should perform the same mock actions you are looking for, does not use Express.js, and i.m.o is a better fit for what you are trying to do:

var http = require('http')
var parseUrl = require('parseurl')
var send = require('send')

http.createServer(function onRequest (req, res) {
  send(req, parseUrl(req).pathname, { root: 'mockData/' })
  .pipe(res)
}).listen(80)
purplestone commented 8 years ago

I'm sorry, I did not described the intentions clear. I took a pseudocode to explain the ajax mock server. Now, I had added app.use( ... if(path.extname(req.path)==='.do||.json'){toSendFile()} ... ) before serve-static, and it works good, Thank you.