一个非常简单的页面... server.js
var path = require("path");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.listen(8000, function() {
console.log("listening on port 8000");
})
app.use(bodyParser.urlencoded());
app.use(express.static(path.join(__dirname, "./static")));
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index');
})
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/basic_mongoose');
var QuoteSchema = new mongoose.Schema({
name: String,
quote: String
})
var Quote = mongoose.model('Quote', QuoteSchema);
app.post('/quotes', function(req, res) {
console.log("POST DATA", req.body);
var quote = new Quote({name: req.body.name, quote: req.body.quote});
quote.save(function(err) {
if(err) {
console.log('something went wrong');
} else {
console.log('successfully added a quote!');
res.redirect('/main');
}
})
})
index.ejs
<html>
<head>
<title></title>
</head>
<body>
<div id='container'>
<h2>Welcome to Quoting Dojo</h2>
<form action='/quotes' method='post'>
<p>Your Name: <input type = 'text' id ='name'/><p>
<p>Your Quote: <input type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>
<button id='skip'>Skip to </button>
</div>
</body>
</html>
单击“提交”按钮后,我收到“无法/ POST”。任何人? 服务器加载,chrome中的html页面显示出来。我填写框并单击“添加”。我得到路由http://localhost:8000/quotes并且错误无法POST /引用。我不知道我做了什么,因为我在服务器中有/'post'到/ quotes和app.post。我不知道我是否还有其他问题。感谢。
答案 0 :(得分:0)
使用name属性而不是id,name发送到服务器,id不是。
答案 1 :(得分:0)
<form action='/quotes' method='post'>
<p>Your Name: <input name='name' type = 'text' id ='name'/><p>
<p>Your Quote: <input name='quote' type='text' id ='quote'/><p>
<button id='add' type='submit'>Add Quote</button>
</form>