javascript - 如何使用node.js和express.js向mongo db atlas发出post请求

标签 javascript node.js mongodb express

我正在尝试使用 Node.js、Express.js 和 Mongoose.js 向 Mongo Db Atlas 发出简单的发布请求。我填写了表格并发送了请求,但它只是不断加载,没有错误,什么也没有。有人有主意吗?

//Require assets
const express = require('express');
const app = express();
const mongoose = require('mongoose');
let port = 3000;

const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb+srv://michael:<PASSWORD-GOES-HERE>@around-town-vsisv.mongodb.net/admin';
const client = new MongoClient(uri, { useNewUrlParser: true });

client.connect(err => {
    const collection = client.db('around_town_db').collection('events');
   // perform actions on the collection object
    client.close();
});

mongoose.Promise = global.Promise;

var eventSchema = mongoose.Schema({
    eventName: String,
})

var eventData = mongoose.model('Event', eventSchema);

//Load index page using endpoint
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

//Post using endpoint
app.post('/addevent', (req, res) => {
    var userData = {
       eventName: req.body.eventName 
    }
    new eventData(userData)
    .save()
   .then(res => {
     res.send('item saved to database');
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

//Listen on port 3000
app.listen(port, () => {
 console.log('Server listening on port ' + port);
});

下面是提交帖子请求的简单表单。对我所缺少的有什么想法吗?

<!DOCTYPE html>
<html>
 <head>
 <title>Add a local event</title>
 </head>

 <body>
 <div class="app">
    <h1>Add an event</h1>
    <form method="post" action="/addevent">
    <label>Enter event Name</label><br>
    <input type="text" name="eventName" placeholder="Enter event name..." required>
    <input type="submit" value="Add Event">
    </form>
 </div>
 </body>
</html>

最佳答案

好的,看来您有两个问题。首先,您不让 Mongoose 本身连接到您的数据库,其次您要覆盖响应变量。如果您注意到 userData.save() promise 链中的 .then() 回调,您将调用该结果变量“res”以及响应变量“res' 来自路由回调。

要解决第一个问题,请在应用程序启动的某个位置调用一次(而不是当前的 MongoClient 代码)

mongoose.connect(uri)

您还可以使用mongoose.createConnection()如果您想要对连接进行更细粒度的控制,或者需要对不同的数据库建立多个连接。

第二个问题,您的帖子处理程序应如下所示:

//Post using endpoint
app.post('/addevent', (req, res) => {
    var userData = {
       eventName: req.body.eventName 
    }
    new eventData(userData)
    .save()
   .then(result => { // note the use of a different variable name
     res.send(result); // also, you generally want to send *something* down that lets the user know what was saved.  Maybe not the whole object, but this is illustrative and the client will at least need to know something (e.g. the id) to refer to the object by in the future. 
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

与您的问题无关,但大多数人以 RESTful 方式编写 Express API。如果您想遵循该约定,那么您的路线应该看起来更像这样:

GET /events              // list the events
GET /events/:eventId     // get a single event by ID
POST /events             // add a new event
PUT /events/:eventId     // update an existing event
DELETE /events/:eventId  // remove an event

关于javascript - 如何使用node.js和express.js向mongo db atlas发出post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53798888/

相关文章:

javascript - JqueryUI 自动完成 : autoFocus = true won't do anything

javascript - 迭代嵌套的 JavaScript 对象

mongodb - 无法连接到 MongoDB/奇怪

javascript - 为什么无法使用 ajax 调用的响应更新 html img src

javascript - 向 Mongo 发送并行请求,并在所有请求完成后继续

javascript - javascript 中 if 语句被跳过

node.js - 如何连接solr和nodejs?

mongodb - 我可以考虑使用哪些解决方案/模式来存储数百万原始数据?

mongodb - mongoengine - 忽略模式验证的额外字段

javascript - 如何在 HTML 中突出显示鼠标指针处当前渲染的行? (不是表/行)