我正在使用npm请求将数据插入MongoDB - 就像使用表单变量直接注入一样。这是我点击提交按钮后在浏览器中看到的内容: FORM DATA
这是我用来将凭证插入数据库的脚本:
request.post(
'http://127.0.0.1:8081/process_post', {
json: {
fname: 'john',
surname:'smtith',
age:100,
password: '123as',
email: 'email@email.com',
phone: 9283746,
city: 'anywhere',
country: 'AZSW',
postal_code: 117058,
picture: 'something.jpg',
description:'description'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
这是服务器端功能:
app.post('/process_post', urlencodedParser, function (req, res) {
var response = {fname: req.body.fname, surname: req.body.surname, age: req.body.age,
password: req.body.password,email: req.body.email, phone: req.body.phone,
city: req.body.city, country: req.body.country, postal_code: req.body.postal_code,
description: req.body.description, picture:req.body.picture};
//etc
问题是服务器全部弄乱了变量,并对发送的数据进行了随机匹配。此外,在mongo shell中我可以看到数据是“未定义的”......是因为我发送了一个Json而服务器端设置为捕获变量?
编辑:这些是服务器的logs
答案 0 :(得分:0)
首先执行请求正文的json解析:
let reqBody = JSON.parse(req.body)
接下来创建数据模型,例如user:
newUser = new User({
'attr1': reqBody.attr1,
'attr2': reqBody.attr2,
'attrN': reqBody.attrN
});
newUser.save(function storeUser(err, user) {
//TODO: check if the user was saved correctly.
});