nodejs ReferenceError:未定义oneTimeCode

时间:2016-02-15 13:21:36

标签: javascript node.js

我在尝试解析(正文解析器)http post响应时遇到了问题。我想使用oneTimeCode作为变量并在服务器端评估该变量。我收到以下错误:ReferenceError: oneTimeCode is not defined我错过了什么?

nodejs

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var fs = require('fs');
var https = require('https');
var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
  rejectUnauthorized: false
};
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

app.use(bodyParser.urlencoded({ extended: true }));
app.post('/verify', function(request, response) {
  if (oneTimeCode == '123456') {
    response.sendFile('/home/ubuntu/index.html');
  } else {
    response.sendFile('/home/ubuntu/otp.html');
  }
 });
app.get('/', function(request, response){
    response.sendFile('/home/ubuntu/otp.html');
});
https.createServer(options,app).listen(443);

otp.html

<!DOCTYPE html>
<html>
<title>OTP</title>
<body>
<h1>OTP</h1>
<form action="https://1.2.3.4.com/verify" method="post" target="_blank">
  OTP <input type="text" name="oneTimeCode"><br>
  <input type="submit" value="Submit">
</form>

<p>Click on the submit button.</p>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

oneTimeCode不会被声明为全局变量,它将在request.body中可用。

你可以这样:

app.post('/verify', function(request, response) {
  var oneTimeCode = request.body.oneTimeCode; // Now you have your variable
  if (oneTimeCode == '123456') {
    response.sendFile('/home/ubuntu/index.html');
  } else {
    response.sendFile('/home/ubuntu/otp.html');
  }
 });

答案 1 :(得分:1)

使用request.body.oneTimeCodebodyParser增强request变量