下面的代码非常混乱,所以不要判断太多!我正在尝试将一个基本的用户个人资料发布到我的数据库中,我不认为我很远,但我一直得到404.
我很了解所有这些技术,所以有人可以告诉我我做错了什么。node.js POST方法
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/local';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('signIn', { title: 'signIn' });
});
router.get('/getData', function(req, res, next){
mongo.connect(url, function (err, db) {
assert.equal(null, error);
var cursor = db.collection('userData').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
} );
});
});
router.post ('/insert', function(req,res,next) {
var item = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
password: req.body.password
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('userData').insertOne(item, function (err, result) {
assert.equal(null, err);
console.log('item has been inserted');
db.close;
});
});
res.redirect('/');
});
module.exports = router;
表单HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>SignIn Page</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/signIn.css"/>
</head>
<body>
<div class="background">
<div class="loginFormWrapper">
<form action="/users/submit" method="POST">
<div class="loginForm">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="first name">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="last name">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="password">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="users" method="GET">
<button type="submit" class="btn btn-default">get result</button>
</form>
</div>
</div>
</body>
</html>
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var validate = require('form-validate');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var About = require('./routes/about');
var signIn = require('./routes/signIn');
var contact = require('./routes/contact');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/About', About);
app.use('/signIn', signIn);
// app.use('/contact', contact);
//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
user.js
var express = require('express');
var app = require("mongoose");
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
答案 0 :(得分:1)
您已发布到网址users/submit
,但我看不到users/submit
的任何API。您曾说过使用/users
网址的用户,但您是否在/submit
内定义了/users
?
你可以通过这个 Routing in expressjs
答案 1 :(得分:1)
快速提醒一下,post()方法仅从您指定的<form>
获取数据。为了能够获取这些数据,您必须执行以下操作。
app.js
const express = require('express)
const mongoose = require('mongoose)
var app = express()
mongoose.connect('mongodb://localhost:"yourPortHere"/"mongoDBhere"')
现在,发布需要身体分析器,以便能够检索数据并将其“转换”为JS,因为您需要身体分析器。
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
现在让我们来看看
app.post("/action", (req, res) => {
var userData = {
username: req.body.username,
password: req.body.password
}
目前,userData将保留您刚从<form>
检索到的数据
请记住,action="/YourActionHere
是app.post("/YourActionHere")
的标识符,因此这两个必须匹配,否则您将无法获取数据。
要将其保存到MongoDB,首先需要创建要存储的对象的模型,如果MongoDB上有一个名为电影的数据库,并且其目录名为 films 它首先必须创建一个名为 film 的模型,因为猫鼬会将其保存在 films 目录中(<-按目录表示我的收藏)
所以:在文件夹模型中,您将创建对象的模型
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var film = new Schema({
title: String,
year: String,
director: String
})
module.exports = mongoose.model("movie", movieSchema)
要能够使用该新模式,必须使用以下命令将其导入到app.js中:
var Film = require('pathToFilmSchema')
现在在您的帖子中,您将userData保存到该Schema,猫鼬会将其存储在.js中指定的集合中。
app.post("/action", (req, res) => {
var userData = {
title: req.body."name",
year: req.body."name",
director: req.body.""
}
new Film(userData)
})
如果结构相同,则该变量中的Data将存储在Schema中,那么您只需调用方法.save()
,就可以像这样直接调用
newFil(userData)
.save()
现在,猫鼬会将带有电影模式的新对象存储到您在顶部连接的数据库中。请记住,如果没有名为film的集合,则mongoDB将创建一个名为 films 的集合(始终为复数)并将Schema存储在该集合中。
保存后,您可以res.redirect()
到“ /”或呈现另一个页面,这取决于您。
答案 2 :(得分:0)
在app.post
函数中,您应该具有以下内容:
let MongoClient = require('mongodb').MongoClient;
let connectionUrl = "mongodb://localhost:27017/";
// or
// let connectionUrl = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
// creating the message object
let obj = {"text" : "Something"};
console.log("OBJ: " + obj);
MongoClient.connect(connectionUrl, function(err, client) {
if (err) throw err;
console.log("Connected correctly to server");
// if database and collection do not exist they are created
var db = client.db('YourDatabase')
db.collection("YourCollection").insertOne(obj, function(err, res) {
if (err) throw err;
console.log("1 message inserted");
client.close();
});
});