编程语言
首页 > 编程语言> > javascript-如何使用快速框架从Node.js中的请求中获取字段?

javascript-如何使用快速框架从Node.js中的请求中获取字段?

作者:互联网

我正在编写Node.js脚本,并且在集成“登录”表单时遇到问题.我可以使用静态HTML页面来完成此操作,但是使用动态“ .ejs”页面会导致问题…我的表单字段报告为“未定义”.

var helmet = require('helmet');
var bodyParser = require('body-parser')
//var cookieParser = require('cookie-parser');
//var csurf = require('csurf');
//Use Express module
var express = require('express');
var app = express();
var io = require("socket.io");  //web socket external module
var easyrtc = require("easyrtc");  //EasyRTC external module

app.use(helmet());

//Statically serve files in these directories
app.use("/js", express.static(__dirname + '/easyrtc/js'));
app.use("/images", express.static(__dirname + '/easyrtc/images'));
app.use("/css", express.static(__dirname + '/easyrtc/css'));

//For my homepage  
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs')  //set the view engine to ejs

app.use("/css", express.static(__dirname + '/public/css'));
app.use("/img", express.static(__dirname + '/public/img'));

//Needed to parse form data 
app.use(bodyParser()); 

//var csrfProtection = csurf({ cookie: true });  
//parse cookies...we need this because "cookie" is true in csrfProtection
//app.use(cookieParser());

//global variables 
var loggedIn = false,
    password = 'password';  
var title = 'This is a heading';
var message = 'Steve is NOT available';
var presenter = 'Username'
var passport = 'Password'    


//Temporary home page
app.get('/', function (req, res) {

var site = req.hostname;  //example returns "localhost"
var splits = site.split(".");  //"split" on "periods"

console.log("site is: " + site);
console.log("first split is: " + splits[0]);
console.log("second split is: " + splits[1]);

if (loggedIn == true) {
res.render('index', {title: 'available', message: 'Steve is available...'});
console.log("homepage -logged in");
}
else {
console.log("homepage -not logged in");
  res.render('login', {
    usr: {},
    pword: {},
    data: {},
    errors: {}//,
//        csrfToken: req.csrfToken()
  });
 }
});

//Respond to POST from login form
app.post('/login', function (req, res) {
console.log('post to /login');

var usr_STR = String(req.body.usr)
var pass_STR = String(req.body.pword)
console.log("req.body.usr: " + req.body.usr + " req.body.pword: " + req.body.pword);
console.log("usr_STR: " + usr_STR + " pass_STR: " + pass_STR);

if (loggedIn == true) {
    res.send("Already logged in.");
}
else {
    console.log("Posted data:" + JSON.stringify(req.body));
    console.log("req.body.pw:" + req.body.pw);
    console.log("req.body.pword:" + req.body.pword);
    console.log("req.body.usr:" + req.body.usr);
    if (req.body.pword == password) {
        loggedIn = true;
        res.send("You are logged in.");
        console.log("Logged in");

        // Start EasyRTC server
        var easyrtcServer = easyrtc.listen(app, socketServer);

    }
    else {

        res.render('login', {
          data: req.body,  //{ presenter, passport }
          errors: {
            presenter: {
            msg: 'Your username does not look right'
            },
            passport: {
            msg: 'Your password does not look right'
            }
          }//,
//              csrfToken: req.csrfToken()
        });

    }
 }
});

//Error Handling
app.use((req, res, next) => {
  res.status(404).send("Sorry can't find that!")
});

app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
});


// Start server on port 8080
var webServer = app.listen(8080);
console.log('Listening on port ' + 80);

// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer);

我看到控制台向我报告以下内容:

Posted data:{}

req.body.pword:undefined

req.body.usr:undefined

我对使用Node.J还是有点陌生​​,显然我对如何将参数从(.ejs)表单传递到req.body中的路由处理程序感到困惑…任何建议将不胜感激,我真的很难尝试解决这个问题.先感谢您.问候.

注意:从我的代码中可以看到,我删除了对“ csurf”和“ cookieparser”的引用,因为在我的早期运行中,此信息是在“ req.body”中返回的…所以我认为它们在某种程度上干扰了.但是,似乎还有其他情况.

这是登录表单的关联HTML:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div class="form-header">
  <% if (Object.keys(errors).length === 0) { %>
  <h2>Login Form</h2>
  <% } else { %>
  <h2 class="errors-heading">Oops, please correct the following:</h2>
  <ul class="errors-list">
   <% Object.values(errors).forEach(error => { %>
    <li><%= error.msg %></li>
   <% }) %>
   </ul>
   <% } %>
</div>


<form method="post" action="/login" novalidate>
<div class="imgcontainer">
<img src="img_avatar2.png" alt="Avatar" class="avatar">
</div>

<div class="container">
<label for="usr"><b>Username</b></label>
<input type="text" placeholder=<%= data.presenter %> name="usr" required>

<% if (errors.presenter) { %>
  <div class="error"><%= errors.presenter.msg %></div>
<% } %>

<label for="pword"><b>Password</b></label>
<input type="password" placeholder=<%= data.passport %> name="pword" required>

<% if (errors.passport) { %>
  <div class="error"><%= errors.passport.msg %></div>
<% } %>

<button type="submit">Login</button>

</div>

<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>

</body>
</html>

解决方法:

您需要使用body解析器,仅导入它是行不通的.
同时结帐body-parser docs

// configure the app to use bodyParser()

// parse urlencoded data type as JSON
app.use(bodyParser.urlencoded({
    extended: true
}));

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));

标签:javascript,node-js,express,body-parser,ejs
来源: https://codeday.me/bug/20191013/1906222.html