【问题标题】:Getting the error "bodyParser.json is not a function" in express app在 express 应用程序中获取错误“bodyParser.json 不是函数”
【发布时间】:2017-03-19 18:58:32
【问题描述】:

我是 nodejs 的新手。在尝试快递时,我被卡住了。我只是想测试我的应用程序。运行 server.js 文件时出现错误。我错过了什么?

这是控制台的样子...

C:\Users\rupindersingh\Dropbox\Works\worthlessmongo>node server.js
C:\Users\rupindersingh\Dropbox\Works\worthlessmongo\server.js:12
app.use(bodyParser.json());
                   ^

TypeError: bodyParser.json is not a function
    at Object.<anonymous> (C:\Users\rupindersingh\Dropbox\Works\worthlessmongo\server.js:12:20)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:974:3

这是 pakage.json 文件

{
  "name": "worthlessmongo",
  "version": "1.0.0",
  "description": "Just Tryin",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.15.2",
    "ejs": "^2.5.2",
    "express": "^4.14.0",
    "mongojs": "^2.4.0"
  },
  "devDependencies": {}
}

Server.js 文件如下:

var express=require('express');
var path=require('path');
var bodyParser=('body-parser');

var index=require('./routes/index');

var app=express();
app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use(express.static(path.join(__dirname,'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/',index);
app.listen(3000,function(){
    console.log('server started at port 3000');
});

【问题讨论】:

    标签: node.js express body-parser


    【解决方案1】:

    在需要 body-parser 时,您没有使用 require

    var express=require('express');
    var path=require('path');
    var bodyParser= require('body-parser');
    

    【讨论】:

      【解决方案2】:

      你必须使用'require'并在括号中使用模块名称...就像一个包含...。

      var bodyParser=require('body-parser');

      【讨论】:

        猜你喜欢
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        • 2019-11-06
        • 2020-10-18
        • 2020-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多