更新:Express.js req.body是一个空对象& req.body.name未定义

时间:2018-05-01 13:27:02

标签: javascript node.js mongodb reactjs express

我不确定我在这里做错了什么,但我从req.bodyreq.body.name得不到任何结果。我只是想从React组件中的输入字段中获取文本。这是我的POST请求:

    //posting notes to backend and storing in db
module.exports = (app,bodyparser,mongoUrl) => {


    let MongoDB = require('mongodb').MongoClient;
    app.use(bodyparser.urlencoded({extended: false}));
    app.use(bodyparser.json());

    app.post('/notes',function(req,res){
        //posting the note just fine, just not receiving the note text (says undefined)
        //not getting note text for some reason?? only returning the date...

        //send response to append note to page
        //store note data in db

        let noteData = {
            text: req.body.name,
            date: new Date().toDateString()
        };
        console.log(req.body);
        MongoDB.connect(mongoUrl,function(err,db){

                let notesCollection = db.collection('notes');
                notesCollection.insert(noteData);
                db.close();
        });

        res.status(201).send(noteData);

    });

}

我的React组件:

class NewNote extends Component {
//this is for creating a new note only
//need post request for this one
//need to clear textarea upon submit or cancel
    render(){
      return (
        <div id="form-container" className='container-fluid' style={defaultStyle}>
          <div id="form">
            <div className="form-group">
            <form action="/notes" method="POST" encType="multipart/form-data">
              <label htmlFor="newNote">New Note:</label>
                <input type="text" name="name" className="form-control" rows="5" id="newNote" placeholder="Write your note here..."></input>
                <button id="done" type="submit" className="btn btn-primary pull-right">Done</button>
                <button id="cancel" className="btn btn-warning pull-right">Cancel</button>
            </form>
            </div>
          </div>
        </div>
      )
    }

}

我的package.json文件:

{
  "name": "quick-notes-app",
  "version": "1.0.0",
  "description": "my first full-stack javascript app",
  "main": "./routes/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon --exec babel-node ./routes/server.js --ignore public/",
    "dev": "webpack -wd",
    "lint": "eslint ./"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/CandiW/quick-notes-app.git"
  },
  "author": "CandiW",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/CandiW/quick-notes-app/issues"
  },
  "homepage": "https://github.com/CandiW/quick-notes-app#readme",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3",
    "mongodb": "^2.2.35",
    "randomcolor": "^0.5.3",
    "react": "^16.3.2",
    "react-dom": "^16.3.2"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "eslint": "^4.19.1",
    "eslint-plugin-react": "^7.7.0",
    "nodemon": "^1.17.3",
    "webpack": "^3.11.0"
  }
}

这是我的server.js文件,我需要body-parser模块:

const express = require('express');
const path = require('path');
const bodyparser = require('body-parser');
const notes = require('./notes.js');
const myNotes = require('./mynotes.js');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

let app = express();
let database = "mongodb://localhost:3000/";

    app.use(express.static('public'));
    app.use(bodyparser.urlencoded({extended: true}));
    app.use(bodyparser.json());

function quickNotesApp(port){
    // eslint-disable-next-line no-console
    console.log("listening on port " + port);

    notes(app,bodyparser,database);
    myNotes(app,bodyparser,database);

    app.listen(port);

}

quickNotesApp(3000);

请原谅我在代码中的评论:)我正在使用它们来跟踪我的待办事项以及每个组件的作用。你们都可以在这里看到我的应用程序的github repo:Quick-Notes-App

更新5/2/2018:

我对body-parser的使用方式以及我在POST请求中如何使用它进行了一些更改(我已更新了我附加的原始代码示例)。此时,当我从数据库返回文档数组时,我仍然收到相同的text: null,当我在console.log req.body时,它仍然是一个空对象。想知道是否有人对React.js是否有问题有任何疑问?例如,我们必须在React Components中使用className而不是class。我找不到任何容易回答这个问题的东西。我还卸载并重新安装了express,body-parser以及其余的所有依赖项都无济于事。

更新2 - 5/2/2018

对于任何可能发现这个有用的人,我发现this Medium article关于如何将Node.js后端与React.js前端结合起来。我想我会尝试一下,看看它是否有帮助。

2 个答案:

答案 0 :(得分:0)

npm i --save body-parser
const body_parser = require('body-parser');
app.use(body_parser.json());
app.use(body_parser.urlencoded({extended: true}));

答案 1 :(得分:0)

另外添加app.use(bodyParser.json());

const express = require('express');
const path = require('path');
const notes = require('./notes.js');
const myNotes = require('./mynotes.js');
const bodyparser = require('body-parser');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;

let app = express();
let database = "mongodb://localhost:3000/";
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());

function quickNotesApp(port){
    // eslint-disable-next-line no-console
    console.log("listening on port " + port);
    app.use(express.static('public'));


    notes(app,database);
    myNotes(app,database);

    app.listen(port);

}

quickNotesApp(3000);