2017-06-21 43 views
0

我有一個非常簡單的html表單和快速服務器,但我無法使路由工作。我總是得到「不能發佈」的消息。我錯過了什麼?爲什麼我仍然收到「無法POST」消息?

var express = require('express'); 
    var bodyparser = require('body-parser'); 
    var path = require('path'); 
    var app = express(); 

    app.use(express.static("public")); 
    app.use(express.bodyParser()); 

    app.get("/", function(req, res){ 
    res.sendFile(path.join(__dirname+"/index.html")); 
    }); 

    app.post("/sendform", function(req, res){ 
    res.send('You sent the name "' + req.query.user + '".'); 
    }); 

    app.listen(3000, function(){ 
    console.log("Server is running at port: 3000"); 
    }); 


    <form method="post" action="http://localhost:3000/sendform"> 
    <input type="text" name="username" /> 
    <input type="submit" value="küldés" /> 
    </form> 

回答

1

使用express 4.15.3,你必須使用body parser有點不同。 我改變你的代碼,這一點,我能對它發帖:

var express = require('express'); 
var bodyParser = require('body-parser'); 
var path = require('path'); 
var app = express(); 

app.use(express.static("public")); 
//app.use(express.bodyParser()); 
app.use(bodyParser.json({ 
    limit: "10mb" 
})); 

app.use(bodyParser.urlencoded({ 
    limit: "10mb", 
    extended: true 
})); 


app.get("/", function (req, res) { 
    res.sendFile(path.join(__dirname + "/index.html")); 
}); 

app.post("/sendform", function (req, res) { 
    res.send('You sent the name "' + req.query.user + '".'); 
}); 

app.listen(3000, function() { 
    console.log("Server is running at port: 3000"); 
}); 
+0

終於來了!謝謝。你能解釋爲什麼我需要這樣做嗎?但是,我的req.query.user返回undefined。我用req.body.name試了一下,但還是一無所獲。 – JustMatthew

+0

中間件已被移出明確,不知道你是如何運行你的代碼,但我得到這個錯誤,與你有確切的代碼:'錯誤:大多數中間件(如bodyParser)不再與Express捆綁在一起,必須單獨安裝。請參閱https:// github.com/senchalabs/connect#middleware' –

+0

好吧,我已經設法做到了。我不得不重新啓動我的服務器。再次感謝你:) – JustMatthew

相關問題