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

req.body value undefined for form field value set by javascript function

我正在构建 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() 将表单中的值设置为纬度 (id="latVal") 和经度 (id="longVal") returned 来自 API称呼。这些值出现在表单域中。从这里我想将这些值保存到 MongoDB 中的用户配置文件数据中,我试图通过单击触发下面功能的“保存”按钮在 routes.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 return 未定义的建议解决方案后,我尝试了

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

我认为添加上面两行行不通,因为 API 编辑的值 return 不是 JSON 格式。这没有用。我检查了 typeof 的纬度和经度,它是一个数字。我不确定为什么 req.body 没有获取值。

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

我发现最接近我的问题的是 this,它从未得到解决。

非常感谢任何指导,或者甚至更好的方法来实现这一点会很棒。我填充表单字段的原因是因为我想不出另一种方法来将值从前端发送到后端以进行保存。

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());
}

这只是您可以执行的操作的概要。根据您的需要扩展此代码。

你在大部分地方都是正确的,你只需要用 name.that 替换 ID 是 nodejs 能够定位到你的输入字段的唯一方法