尽管我已经安装了 node.js body-parser,为什么调用它仍然失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31836930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:12:59  来源:igfitidea点击:

Why does the call to node.js body-parser fail despite the fact that I have installed it?

node.jsexpressbody-parser

提问by Martin K

I'm beginning to learn node.js and trying to work out how to get the contents of a POST request. I am trying to follow the instructions in this post. So far I have successfully installed node.js (on Windows 7) and express, and been able to get my very first script to work. However my problem comes when I try to use body-parser. I have installed it and it appears to be there (here is a screenshot)

我开始学习 node.js 并尝试找出如何获取 POST 请求的内容。我正在尝试按照这篇文章中的说明进行操作。到目前为止,我已经成功安装了 node.js(在 Windows 7 上)和 express,并且能够让我的第一个脚本工作。但是,当我尝试使用 body-parser 时,我的问题就出现了。我已经安装了它,它似乎在那里(这是一个截图)

Here is the code of the node.js script

这是 node.js 脚本的代码

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(express.json());       // to support JSON-encoded bodies

app.get('/', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    res.end('Vous êtes à l\'accueil');
});

app.get('/user/:usernum', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    res.end('You are on page USER with n° : ' + req.params.usernum);
});

// https://stackoverflow.com/questions/5710358/how-to-get-post-a-query-in-express-js-node-js
app.post('/adonis', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    console.log(req.body.title);
//    res.write(JSON.stringify(req));
    res.end('Hopefully I stringified a POST');
});

// ... Tout le code de gestion des routes (app.get) se trouve au-dessus

app.use(function(req, res, next){
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Page introuvable !');
});

app.listen(8091);

Yet when I run it, node.js throws an error saying "cannot find module body-parser". What have I done wrong?

然而,当我运行它时,node.js 抛出一个错误,说“找不到模块正文解析器”。我做错了什么?

As per @Kale's and others' suggestions I tried installing body-parser locally, but this does not seem to help since now my script gives the following message:

根据@Kale 和其他人的建议,我尝试在本地安装 body-parser,但这似乎没有帮助,因为现在我的脚本给出了以下消息:

Error: Most middleware (like json) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
at Function.Object.defineProperty.get (d:\smartguide\nodejs\node_modules\express\lib\express.js:99:13)
at Object.<anonymous> (d:\smartguide\nodejs\oc1.js:5:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3`

I tried installing "json" locally and globally - the install seems to work but it makes no difference to the file error.

我尝试在本地和全局安装“json” - 安装似乎有效,但对文件错误没有影响。

采纳答案by Martin K

I think I was doing something fundamentally wrong - I went back to basics and started all over again, this time making sure I had a package.json file. Now it works.

我想我在做一些根本错误的事情 - 我回到了基础并重新开始,这一次确保我有一个 package.json 文件。现在它起作用了。

Here is the code:

这是代码:

var express = require('express');
var session = require('cookie-session');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();

var app = express();


// JSON testing
app.post('/json-test', jsonParser, function(req, res) {
    if (!req.body) return res.sendStatus(400);
    console.log(JSON.stringify(req.body));
    console.log(req.body.title);
    res.status(200).send(req.body.title);
    })

// Can't get anything else
.use(function(req, res, next){
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Page introuvable !');
    })


.listen(8090);

And here is the package.json

这是 package.json

{
"name": "todo1",
"version": "0.1.0",
"dependencies": {
    "express": "~4.11.0",
    "ejs": "~2.1.4",
    "cookie-session": "~1.1.0",
    "body-parser": "~1.10.1"
},
"author": "Martin",
"description": "Un gestionnaire de todolist ultra basique"
}

回答by Taylor Swanson

As Kevin B stated, you have to install body-parserlocallyand save it to the manifest:

正如 Kevin B 所说,您必须在body-parser本地安装并将其保存到清单中:

npm install --save body-parser

回答by Mel Lord-Lloyd

This answer is much simpler. Go to the base directory and link to the required global modules.

这个答案要简单得多。转到基本目录并链接到所需的全局模块。

npm link body-parser

There's no need to install modules all over the place. If the module is not installed globally, the above command will install the module globally then link to it locally.

无需到处安装模块。如果模块未全局安装,则上述命令将全局安装模块,然后在本地链接到它。

回答by Rahul Sonone

I was getting the same error where after installing express I am getting errors like

我遇到了同样的错误,在安装 express 后我收到了类似的错误

Cannot find module 'body-parser'after installing this the error is

Cannot find module 'body-parser'安装这个后,错误是

Cannot find module 'merge-descriptors'and so on for

Cannot find module 'merge-descriptors'等等

Cannot find module 'finalhandler'

Cannot find module 'array-flatten'

These all module are dependencies for express. If you execute "npm install" or "npm install -g" without any module it will install all the missing dependencies.

这些所有模块都是 express 的依赖项。如果在没有任何模块的情况下执行“npm install”或“npm install -g”,它将安装所有缺少的依赖项。

To fix this I first uninstall the express and then install the same and immediately after that executed "npm install". This fixed all the errors.

为了解决这个问题,我首先卸载 express,然后安装相同的,然后立即执行“npm install”。这修复了所有错误。