本文介绍了节点JS EJS开机自检的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的部分控制器有进口

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>

编辑:更新了带有导入功能的控制器

Updated my controller w/ imports

推荐答案

在更新的代码段中,您似乎正在使用bodyParser.json,它将仅解析json负载,而不解析作为正文发布。

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 }))

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

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

这篇关于节点JS EJS开机自检的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:56