NodeJS & EJS POST

£可爱£侵袭症+ 提交于 2020-05-16 04:34:52

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/48893686/nodejs-ejs-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!