javascript函数设置的表单字段值的req.body值未定义

时间:2018-12-07 09:43:49

标签: node.js express body-parser

我正在构建一个node.js,express.js和passport.js应用程序。登录到个人资料后,我要求用户单击“获取位置”按钮以获取用户位置。

Profile.ejs

<form action="/testform" method="post" >
  <div class="form-group">
  <input type="text" class="form-control" id="latVal" placeholder="latitude">
  <input type="text" class="form-control" id="longVal" placeholder="longitude">
  </div>
  <button type = "submit" class="btn btn-warning btn-sm">Save</button>
</form>
<button type = "submit" class="btn btn-warning btn-sm" onclick="getLocation()">Get Location</button>

onclick调用位于mapCall.js中的getLocation()函数

function getLocation() 
 …
 //call to showLocation()
} 

function showLocation(position) {
    …
    document.getElementById("latVal").value = latitude; 
    document.getElementById("longVal").value = longitude; 
}

showLocation()将表单中的值设置为从API调用返回的纬度(id =“ latVal”)和经度(id =“ longVal”)。值显示在表单字段中。在这里,我想将这些值保存到MongoDB中的用户配置文件数据中,我尝试通过单击“保存”按钮来触发在下面的功能中在route.js中实现

app.post('/testform', isLoggedIn, function(req, res) {
        user.findById(req.user.id, function(err,user) {
            if(!user) {
                req.flash('error', 'No accound found');
                return res.redirect('/profile');
            }
            user.location.latitude = req.body.latVal;
            user.location.longitude = req.body.longVal;

            user.save(function(err){
                res.redirect('/profile');
            });
        });
    });

当我console.log req.body.latVal和req.body.longVal时,这些变量的值是不确定的。什么都没有保存在数据库中。

在server.js中,我有

var bodyParser = require('body-parser');
app.use(bodyParser());

在研究提出的解决方案以使req.body返回我尝试过的未定义

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

我认为添加以上两行并不可行,因为API返回的值不是JSON格式。这没有用。我检查了typeof的经度和纬度,它是一个数字。我不确定为什么req.body没有拿起价值。

我最初的猜测是app.post尝试在API返回值之前读取值,在这种情况下,req.body.latVal将读取一个空字段。我添加了保存按钮以测试该理论,这也证明是错误的。

我发现与问题最接近的是this,但从未解决。

任何指导都将受到高度赞赏,甚至有更好的方法来实现这一目标也将是很棒的。我填写表单字段的原因是因为我想不出另一种将值从前端发送到后端进行保存的方法。

2 个答案:

答案 0 :(得分:2)

name属性添加到您的输入中。

<input type="text" class="form-control" id="latVal" placeholder="latitude" name="latVal">
<input type="text" class="form-control" id="longVal" placeholder="longitude" name="longVal">

编辑:(根据评论)

您可以在getLocation()调用之后对服务器进行AJAX调用。

function getLocation() {
    ///you get the lat and long
    showLocation(position)
    saveLocation(latitude, longitude)
    .then(function(resp){
        //do something with resp
    })
}
function saveLocation(latitude, longitude) {
    //we have native fetch in newer browsers, so
        return fetch("/testform", {
            method: "POST",
            headers: {
                "Content-Type": "application/json; charset=utf-8", //if this doesn't work use the below one
                // "Content-Type": "application/x-www-form-urlencoded",
            },
            body: JSON.stringify({latitude,longitude}), // body data type must match "Content-Type" header
        })
        .then(response => response.json());
}

这只是您可以做什么的概述。将此代码扩展到您的需求。

答案 1 :(得分:0)

在大多数情况下您是正确的,只需将ID替换为name。这是nodejs能够定位到输入字段的唯一方法