首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js - 如何通过附加字符串从request.body访问表单数据?

Node.js - 如何通过附加字符串从request.body访问表单数据?
EN

Stack Overflow用户
提问于 2018-08-24 06:14:43
回答 1查看 0关注 0票数 0

这是html的示例表单

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
    <h1>Send an email</h1>
    <form action="/myaction" method="post">
        <fieldset>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" placeholder="Enter your full name" />

            <label for="email">Email:</label>
            <input type="email" id="email" placeholder="Enter your email address" />

            <label for="message">Message:</label>
            <textarea id="message" placeholder="What's on your mind?"></textarea>

            <input type="submit" value="Send message" />

        </fieldset>
    </form>
</div>
</body>
</html>

这是在服务器上运行的node.js函数:

代码语言:javascript
复制
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.post('/myaction', function (req, res) {
var myString="name";
    console.log(req.body.myString);
    res.end("thanks\n");
})

输出是

代码语言:javascript
复制
undefined

但是当我输出console.log(request.body)时,会显示输入值。我在这做错了什么?是不是可以将字符串附加到request.body。请帮忙

EN

回答 1

Stack Overflow用户

发布于 2018-08-24 16:11:10

你在这里做的是试图在命名的req.body中找到一个myString字段。如果要使用字符串选择字段,可以将对象视为使用字符串索引的数组。所以在你的情况下它将是:

代码语言:javascript
复制
app.post('/myaction', function (req, res) {
 var myString="name";
 console.log(req.body[myString]);// notice how we get the value of req.body here
 res.end("thanks\n");
});

这将使值成为变量myString并使用它为对象编制索引,就像你写的那样:req.body['name']

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档