我在处理来自 Post 表单的 req 时遇到问题。
表单看起来像那样
<form action="/" method="POST">
<div class="form-group">
<label for="city-input">City name</label>
<div class="col-10">
<input class="form-control" type="text" id="city-input" name="map-city">
</div>
<input type="checkbox" aria-label="..."/>
<label style="color: #737373;font-family: 'Open Sans', sans-serif;line-height: 30px;">Choose or type</label>
</div>
<div class="form-group">
<label for="example-text-input">Symbol</label>
<div class="col-10">
<input class="form-control" type="text" id="example-text-input" name="map-symbol">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
我尝试将每个值保存到一个可复制的值中
router.post('/', jsonParser, function(req, res, next){
var test = req.body;
var test0 = test.map-city;
var test1 = test.map-symbol;
});
当我检查什么是 req.body 时,我得到
Object{map-city: "downtown", map-symbol: "dt"}
如何处理以将每个属性保存到字符串
现在我收到错误 - 引用错误:未定义城市
谢谢
使用点表示法在这里不起作用,因为如果您尝试使用点表示法访问带有连字符的对象属性(这通常称为烤肉串情况(,javascript 将引发错误。您应该改用括号表示法:
var test0 = test['map-city'];
var test1 = test['map-symbol'];
Object{map-city: "downtown", map-symbol: "dt"}
将输入标记中的 name 属性更改为 map_city
,它将起作用。
<input class="form-control" type="text" id="city-input" name="map_city">
节点将您的代码理解为 test.map 减去城市(-
被视为减法符号(。相同的逻辑也适用于其他输入字段。