开发者

POST Request Issue in ExpressJS

I'm working with NodeJS and I'm working on letting users upload files. Right now though I'm having a lot of problem even trying to get a simple POST request.

Over in my index.ejs file I have some code that creates a form and then sends a post request:

<div id="uploaddiv">Upload things here<br>
<form action="/upload" enctype="multipart/form-data" method="post">
<input开发者_StackOverflow type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
</div>

Then in server.js, I have code that handles the uploading.

var server = express.createServer();
//bunch of stuff left out
server.get('/upload', function(req, res) {
console.log("uploading!");
if (req.method.toLowerCase() == 'post') {
    res.write('lol');
}
});

My problem is that navigating directly to localhost/upload will console.log properly, but clicking on the button gives me the error "Cannot POST /upload".

Thanks!


server.get means handle an HTTP GET. You want server.post. FYI the "Cannot XXX /uri" error is what express responds with when no active route matches the request and no 404 error handler has been configured.


By using server.get(), you're instructing that route to only respond to GET requests, but the form is obviously a POST.

You should use server.post().

You can also use server.any() if you want to it respond to both GET and POST (and every other HTTP verb as well).


You should probably use Felix Geisendörfer's node-formidable to upload files.

var express     = require('express'),
    app     = express.createServer(),
    util        = require('util'),
    formidable  = require('formidable');

app.get('/upload', function (req, res){
    res.writeHead(200, {'content-type': 'text/html'});
    res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>');
});

app.post('/upload', function (req, res) {
    var form = new formidable.IncomingForm();
    form.uploadDir = '.';
    form.keepExtensions = true;

    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
    });
    return;
});

app.listen(3000, '127.0.0.1');

It is just a simple as this to do file uploading thanks to node-formidable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜