[英]How to fetch data from, mongodb to html form fields?
database name is test1 and collection name is feedbacks
this is app.js
我無法在HTML表單字段中插入mongodb數據,但我想在表單中獲取初始值可以幫助我解決這個問題。因為我對此並不陌生,所以我希望有一個簡單的顯式解決方案。
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017/test1');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
app.get('/retrieve', function(req, res){
post.find({}, function(err, feedbacks){
if(err) res.json(err);
else res.render('retrieve', {posts: feedbacks});
});
});
app.post('/post-feedback', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
var dd = db.db("test1");
dd.collection('feedbacks').insertOne(req.body);
});
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
var dd=db.db("test1");
dd.collection('feedbacks').find({"Name":"shubham"}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
});
});
app.get('/view-sahil', function(req, res) {
dbConn.then(function(db) {
var dd=db.db("test1");
dd.collection('feedbacks').insertOne({"name":"sahil","E-mail":"sahil@vibhuti.guru","comment":"jhdsfji"},function(feedbacks) {
res.status(200).json("Data inserted");
});
});
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
這是我的index.html
<!doctype html>
<html lang="en">
<head>
<script src="..app.js"></script>
<meta charset="UTF-8">
<title>mongodb</title>
</head>
<body>
<h1>Please fill data in the form below:</h1>
<form method="POST" action="/">
<label>Name:<input type="text" name="" value= feedbacks.name required></label>
<br>
<label>Email:<input type="text" name="Email" value="" required></label>
<br>
<label>Comment:<br><textarea name="comment"></textarea></label>
<br>
<input type="submit" value="Submit">
</form>
<a href="/view-feedbacks">View Records</a>
<a href="/view-sahil">insert dummy record </a>
</body>
</html>
您可以像這樣從angularjs調用API
var testApp = angular.module('testApp', []);
testApp.controller('testController' , function ($scope, $http) {
$scope.getRequest = function () {
console.log("I've been pressed!");
$http.get("http://localhost/view-feedbacks")
.then(function successCallback(response){
$scope.response = response;
// Print this value in html
}, function errorCallback(response){
console.log("Unable to perform get request");
});
};
});
使用jQuery,您可以這樣做
$.ajax({
type: "GET",
url: "http://localhost/view-feedbacks",
dataType: "json",
success: function(resp){
console.log("resp", resp);
},
error: function(e){
alert('error', e);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.