简体   繁体   中英

NodeJS & EJS POST

I'm using NodeJS/Express and EJS to create a form to an API route. When I try a POST request and call req.body.password & req.body.confirm , I get "undefined".

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());

Part of my Controller 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>

EDIT: Updated my controller w/ imports

Looking at your updated code snippet you seem to be using bodyParser.json which will only parse json payloads and not form data posted as body.

To accept form submissions you will also need to do something like:

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

It is working for you through postman because I am assuming that when using postman you are submitting json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM