我正在尝试使用POST
方法获取键盘字符串并将其保存在mongoDB中。服务器已启动,但我无法将输入写入数据库,因为控制台返回以下错误:
TypeError : Cannot assign to read-only property '_id' of {the text that I entered through html page}.
我从很少开始使用nodejs和mongodb,我需要帮助......感谢您的关注:))
server.js:
const express = require('express');
const bodyParser= require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var MongoClient = require('mongodb').MongoClient
var assert = require('assert');
var url = 'mongodb://localhost:27017/data';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
app.listen(3000, function() {
console.log('listening on 3000');
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});
app.post('/process_post', function(req, res){
response={r:req.body.s};
var risp=JSON.stringify(response);
res.end(risp);
console.log("Insert : "+risp);
//"text" is an existing collection of mongodb "data" locally
var collection = db.collection('text');
collection.insert(risp);
});
});
db.close();
});
的index.html:
<!DOCTYPE html>
<html>
<body>
<form action = "http://127.0.0.1:3000/process_post" method = "POST">
Input: <input "text" name=s > <br>
<button type = "submit">Submit</button>
</form>
</body>
</html>
答案 0 :(得分:1)
发生错误是因为您尝试将字符串添加到数据库中。你应该插入对象。不要插入risp
,而是尝试插入response
var并查看它是否有效。另请注意,插入是异步的,因此请考虑添加回调函数。见this example,方法不同但逻辑应该相同。