NodeJS& EJS POST

时间:2018-02-20 20:28:46

标签: node.js express ejs

我正在使用NodeJS / Express和EJS为API路由创建表单。当我尝试POST请求并调用req.body.password& req.body.confirm,我得到“未定义”。

index.js

import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
const LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');

import config from './config';
import routes from './routes';

let app = express();
app.server = http.createServer(app);

//middleware
app.use(bodyParser.json({
  limit: config.bodyLimit
}));

//EJS VIEWS CODE
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(flash());

我的控制器的一部分w / imports

import mongoose from 'mongoose';
import { Router } from 'express';
import Account from '../model/account';
import bodyParser from 'body-parser';
import passport from 'passport';
import config from '../config';
import express from 'express'
var async = require("async");
var nodemailer = require("nodemailer");
var crypto = require("crypto");

      if(req.body.password === req.body.confirm) {
          account.setPassword(req.body.password, function(err) {

EJS

<div class="row">
    <div class="col-md-12">
        <form action="http://localhost:3005/v1/account/reset/<%= token %>" method="POST">
          <legend>Reset Password</legend>
          <div class="form-group">
            <input type="password" name="password" value="" placeholder="New password" id="password" autofocus="autofocus" class="form-control"/>
          </div>
          <div class="form-group">
            <input type="password" name="confirm" value="" placeholder="Confirm password" id="confirm" class="form-control"/>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary">Update Password</button>
          </div>
        </form>
    </div>
</div>

编辑:更新了我的控制器w / imports

1 个答案:

答案 0 :(得分:3)

查看更新后的代码段,您似乎正在使用bodyParser.json,它只会解析json有效负载而不是form data作为正文发布。

要接受表单提交,您还需要执行以下操作:

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

它通过邮递员为你工作,因为我假设你在使用邮递员时提交了json。