node.js - 在 mongodb 中发布不会显示整个项目
问题描述
在我下面的应用程序中,连接到 mongodb 我创建了一个发布请求来管理我的 html 文件中的表单。
当涉及到 console.log 时,发布进展顺利,我清楚地看到正在创建的对象。我的问题是它在 mongodb 中只写“电子邮件地址”,我想要“名称”和“部门”。
请注意,我不是故意使用 express,这是我为学习
app.js 所做的评估:
const http = require('http')
// we need fs because each http request will ba handled by creating a readstream and piping it to response
// fs will read the file to be piped
const fs = require('fs')
const mongoose = require('mongoose')
const { parse } = require('querystring')
const { request } = require('http')
// connect to DB
mongoose.connect('mongodb+srv://baptiste:Tractor5@cluster0.myfpj.mongodb.net/DB-Test-made-contact?retryWrites=true&w=majority', {useMongoClient: true})
// checking if DB is properly connected
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error'))
db.once('open', function(){
console.log('db connected')
})
// schema for DB - like a blueprint of everything that will be saved in it
const madeContactSchema = new mongoose.Schema({
name: String,
dept: String,
email: String
})
const MadeContact = mongoose.model('MadeContact', madeContactSchema)
const server = http.createServer(function(req, res){
console.log('Request was made at ' + req.url)
if(req.url === '/' || req.url === '/home'){
// home page
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/index.html').pipe(res)
} else if(req.url === '/contact'){
// create a if statement to manage the post request (not sure about this part but let's try)
if(req.method === 'POST'){
// we state that body is empty
let body = ''
// on event 'data' a chunk of data is sent to body and stringified
req.on('data', chunk => {
body += chunk.toString()
//on the end of stream, we parse the body and console,log it
})
req.on('end', () => {
console.log(parse(body))
// create a const in order to allow us to post into mongodb
const newMadeContact = MadeContact(parse(body)).save(function(err){
if (err) throw err
console.log('Item saved')
})
})
// trying to redirect to contact-successafter posting
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/contact-success.html').pipe(res)
} else{
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/contact.html').pipe(res)
}
} else if(req.url === '/contact-success'){
// page to be displayed once the form is submited with POST request
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/contact-success.html').pipe(res)
console.log(madeContact)
} else {
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/404.html')
}
})
// configuring the port and address of the localhost
// I chose 3000 here because another app is on 8000 and sometimes the cache does weird stuff
server.listen(3000, '127.0.0.1')
// just a quick console feedback that we're conencted on the right port
console.log('Now listening to port 3000')
联系人.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<nav>
<p><a href="/">Home page</a></p>
<p><a href="/contact">Contact</a></p>
</nav>
<h1>Contact me!</h1>
<p>Let's get in touch!</p>
<form action="/contact" method="POST">
<label for="name">Who do you want to contact?</label><br>
<input type="text" id="name" name="name"><br>
<label for="dept">Which Department?</label><br>
<input type="text" id="dept" name="department"><br>
<label for="email">Your email address:</label><br>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
提前感谢您的任何提示:)
我也试着写如下,没有写任何东西:
if(req.method === 'POST'){
// we state that body is empty
let body = ''
// on event 'data' a chunk of data is sent to body and stringified
req.on('data', chunk => {
body += chunk.toString()
//on the end of stream, we parse the body and console,log it
})
req.on('end', () => {
console.log(parse(body))
// create a const in order to allow us to post into mongodb
const newMadeContact = MadeContact({
name: body.name,
dept: body.dept,
email: body.email
}).save(function(err){
if (err) throw err
console.log('Item saved')
})
})
解决方案
if(req.method === 'POST'){
// we state that body is empty
let body = ''
// on event 'data' a chunk of data is sent to body and stringified
req.on('data', chunk => {
body += chunk.toString()
//on the end of stream, we parse the body and console,log it
})
req.on('end', () => {
console.log(parse(body))
// create a const in order to allow us to post into mongodb
const result=parse(body);
const newMadeContact = MadeContact({
name: result.name,
dept: result.department, //check your form input field
email: body.email
}).save(function(err){
if (err) throw err
console.log('Item saved')
})
})
首先我解析了正文并分配给常量(结果)然后另一个更改是 result.department 因为您已将部门命名为表单中的输入字段
推荐阅读
- python - 如何聚合字典列表中的某些元素
- go - 如何在 Go 中将文件压缩为没有目录文件夹的 .zip
- excel - VBA代码在可见单元格中粘贴特殊值
- api - Twiitter python API 无法连接流式传输
- git - 尝试通过 SSH 克隆使用了错误的公钥
- ios - Swift - 如何确定 collectionView 的 scrollView.content.y?
- bash - 为什么以下字符串比较会返回不同的结果?
- r - Shiny:渲染输出时如何防止输入重复?
- python - 如何使用 Shopify Python API 包装器对结果进行分页
- python - 如何自定义pytorch数据