gpt4 book ai didi

node.js - 通过 URL POST 到 mongodb

转载 作者:可可西里 更新时间:2023-11-01 09:35:01 25 4
gpt4 key购买 nike

我正在尝试通过浏览器的 URL 将数据发布到 mongo 数据库。我只能使用 expressJS 才能让它工作,但我很难让它与 mongodb 一起工作。我对此还是很陌生,所以我希望我只是缺少一个简单的组件并且我至少在正确的轨道上。

当我在 url 中输入“http://localhost:27017/api/users?id=4&token=sdfa3”或“http://localhost:27017/nodetest5/api/users?id=4&token=sdfa3”时,我希望在网页上看到“4 sdfa3”。现在我刚收到一个网页,其中包含以下消息:“看起来您正在尝试通过 native 驱动程序端口上的 HTTP 访问 MongoDB。”

这是我的 server.js 文件:

// packages
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var app = express();
var bodyParser = require('body-parser');

//db stuff
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest5');

app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded

//make accessible mongo db accessible to router
app.use(function(req, res, next){
req.db = db;
next();
})

// routes
app.get('/api/users', function(req, res) {
//get values from URL
var id = req.param('id');
var token = req.param('token');
res.send(user_id + ' ' + token + ' ');
});

// POST to localhost
// parameters sent with
app.post('/api/users', function(req, res) {
//internal DB value
var db = req.db;

//values from URL
var user_id = req.body.id;
var token = req.body.token;

//set collection
var collection = db.get('usercollection');

//Submit to DB
collection.insert({
"id" : id,
"token" : token
}, function (err, doc){
if (err) {
res.send("Error encountered when trying to add entry to database.");
}
else {
res.send(user_id + ' ' + token + ' ');
}
});
});

谢谢!

最佳答案

可以通过端口号 28017 访问 MongoDB 的 HTTP 接口(interface)。您需要向 mongod 提供 --rest 选项:

`$ mongod --rest`

您可以在 HTTP Interface documentation 中阅读更多内容.

使用 HTTP 接口(interface)时应谨慎行事。来自 MongoDB 文档:

WARNING
Ensure that the HTTP status interface, the REST API, and the JSON API are all disabled in production environments to prevent potential data exposure and vulnerability to attackers.

关于node.js - 通过 URL POST 到 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37666712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com