如何将 body-parser 与 LoopBack 一起使用?

How can I use body-parser with LoopBack?

我看到 LoopBack 内置了 Express 3.x 中间件。事实上,body-parser 在 loopback/node_modules 中。但我不知道如何将它用作中间件。我从未使用过 Express 3.x,所以也许就是这样。 require 显然不起作用,除非我将 body-parser 作为依赖项安装在我的项目中。

server.js中我应该怎么做才能使用body-parser来将网页表单解析成req.params?这就是它的作用,对吧?

经过数小时的挫折,我将它添加到 middleware.json 中,如下所示:

"parse": {
    "body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}
}

它是作为依赖项安装的。现在我的路线中有 req.body 中的表单数据。我的 server/boot/routes.js 看起来像这样:

module.exports = function(app) {
    app.post('/mailing_list', function(req, res) {
        console.log(req.body.email);
        res.send({"status": 1, "message": "Successfully added to mailing list."})
    });
}

只是为了更清楚地了解如何让这个工作正常进行(因为在找到这个答案后我仍然挣扎了一段时间!),以下是我采取的步骤:

如上所述,在 $APP_HOME/server/middleware.json 中,将 body-parser 添加到 "parse" 部分:

{
  "initial:before": {
    "loopback#favicon": {}
  },
  "initial": {
    "compression": {},
    "cors": {
      "params": {
        "origin": true,
        "credentials": true,
        "maxAge": 86400
      }
    }
  },
  "session": {
  },
  "auth": {
  },
  "parse": {
    "body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}
  },
  "routes": {
  },
  "files": {
  },
  "final": {
    "loopback#urlNotFound": {}
  },
  "final:after": {
    "errorhandler": {}
  }
}

接下来,我将解析器设置添加到 $APP_HOME/server/server.js:

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

var boot = require('loopback-boot');

var app = module.exports = loopback();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data

app.start = function() {
...
...
cont'd

然后,因为我不想弄乱自定义路由,我将以下内容添加到 $APP_HOME/common/models/model.js:

module.exports = function(Model) {

  Model.incoming = function(req, cb) {
    cb(null, 'Hey there, ' + req.body.sender);
  }
  Model.remoteMethod(
    'incoming',
    { accepts: [
      { arg: 'req', type: 'object', http: function(ctx) {
        return ctx.req;
      } 
    }],
    returns: {arg: 'summary', type: 'string'}
    }
  );
};

我现在可以 运行 我的应用程序 $> slc 运行 。

当我 post 到端点时,它现在得到了正确的解析,一切都很好。我希望这对其他人有帮助!

我发帖仅供参考。我 运行 遇到了同样的问题,发现这也有效。您可以使用以下内容在 server/boot/ 目录中添加一个文件:

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

module.exports = function(app) {
  app.use(bodyParser.urlencoded({ extended: true }));
}

当然,你必须通过运行ning安装包:

npm install --save body-parser

这会将包保存在node_modules 目录下。 如果您希望它成为 运行 的第一件事,您可以将文件名以“0”开头,因为它们是按字母顺序加载的。

话虽如此,我认为使用上述中间件配置方法比使用这种方法更 'correct' 和优雅,但如果其他人发现它有用,我会分享它。

我正在使用环回 2.14.0:

要在您的自定义引导脚本路由中使用 body-parser,您只需要:

1) 安装正文解析器 npm install body-parser --save

2) 在middleware.json

中注册模块
"parse": {
"body-parser#json": {},
"body-parser#urlencoded": {"params": { "extended": true }}
},

不需要在 server.js 中设置解析器,当您注册中间件时,loopback 会为您完成此操作。

请注意正文解析器现在已安装在您的源 "node_modules" 目录以及环回模块目录中。

如果可能,尝试按照 loopback documentation.

中的说明注册自定义远程方法

以这种方式注册路由使您可以开箱即用地访问 loopback 的主体解析器,并且是 'cleanest' 实现。

我有不同的测试结果。

1) 对于 json 和 urlencode 类型,无需在 middleware.json 中添加它们的解析器。我可以在不添加 body-parser#json 和 body-parser#urlencoded 的情况下成功地从 req.body 获取数据。 Loopback 应该已经支持它们了。

环回相关源码(我觉得)

1. in strong-remote repo , rest-adapter.js , there is body-parser for json and urlendcoded

line 35
var json = bodyParser.json;
var urlencoded = bodyParser.urlencoded;

line 315
root.use(urlencoded(urlencodedOptions));
root.use(json(jsonOptions));

2. 
remote-object.js
line 33
require('./rest-adapter');

line 97
RemoteObjects.prototype.handler = function(nameOrClass, options) {
var Adapter = this.adapter(nameOrClass);
var adapter = new Adapter(this, options);
var handler = adapter.createHandler();

if (handler) {
// allow adapter reference from handler
handler.adapter = adapter;
}

return handler;
};

2)对于raw类型,我们可以在middleware.json中的"parse"部分添加body-parser#raw,当然需要npm install body-parser .

我的测试代码:

1.My readable stream is from the file uploadRaw.txt , the content is :
GreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaGreenTeaEeeeend

2. middleware.json
"parse": {
"body-parser#raw": {
"paths": [
"/api/v1/Buckets/?/upload"
]
}
},

3.
it('application/octet-stream -- upload non-form', () =>
new Promise((resolve) => {

const options = {

method: 'POST',

host: testConfig.server.host,

port: testConfig.server.port,

path: ${appconfig.restApiRoot}/Buckets/${TEST_CONTAINER}/upload,

headers: {

'Content-Type': 'application/octet-stream',

},
};

const request = http.request(options);

request.on('error', (e) => {
logger.debug(problem with request: ${e.message});
});

const readStream = fs.createReadStream('tests/resources/uploadRaw.txt');

readStream.pipe(request);

resolve();
}));

4.
Bucket.upload = (req, res, options, cb) => {

logger.debug('sssssss in uploadFileToContainer');

fs.writeFile('/Users/caiyufei/TEA/green.txt', req.body, (err) => {

if (err) {

logger.debug('oh, failed to write file');

return;
}

logger.debug('green file is saved!');
});

};

OR

Bucket.upload = (req, res, options, cb) => {

logger.debug('sssssss in uploadFileToContainer');

const writeStream = fs.createWriteStream('/Users/caiyufei/TEA/green.txt');

const streamOptions = {
highWaterMark: 16384,`enter code here`
encoding: null,
}

streamifier.createReadStream(Buffer.from(req.body), streamOptions).pipe(writeStream);

};

5. package.json

"body-parser": "^1.17.1",

"streamifier": "^0.1.1",

也可以像这样在 loopback 中使用 express 框架的内置解析器,例如 json 解析: app.use(app.loopback.json());

根据 Ben Carlson 的回答,您必须

npm install --save body-parser multer

然后在您的 server.js 中需要模块:

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

并在 app.start:

之前使用它们
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer().any()); // for parsing multipart/form-data

然后就可以创建远程方法了:

App.incoming = function (req, cb) {
    console.log(req);
    // the files are available as req.files.
    // the body fields are available in req.body
    cb(null, 'Hey there, ' + req.body.sender);
}
App.remoteMethod(
    'incoming',
    {
    accepts: [
        {
        arg: 'req', type: 'object', http: function (ctx) {
            return ctx.req;
        }
        }],
    returns: { arg: 'summary', type: 'string' }
    }
);

使用此功能,您可以上传文件和其他数据字段以使用 multipart/form-data 环回。

在 Loopback ^3.22.0 中,我可以通过添加

"parse": {
    "body-parser#json": {}
  },

到server/middleware。json 为了在 server/boot/routes.js

中消耗 application/json post 个实体
module.exports = function(app) {
  app.post('/api/sayhello', function(req, res, next) {
     console.log(req.body)