【问题标题】:Azure Mobile App node.js backend - Cannot get content of requestAzure 移动应用 node.js 后端 - 无法获取请求内容
【发布时间】:2016-04-26 15:15:18
【问题描述】:

我想在 Azure 移动应用 Node.js 后端服务器中使用简单的 api。 但是经过努力却无法得到请求的内容。

谁能告诉我任何可能丢失的东西?

这是我的 api (myApi.js):

module.exports = {
    "post": function (req, res, next) {
        for (var k in req) {
            console.log("%s: %j", k, req.k);
        }
        res.status(200).send('post');
    }
}

这是我的 app.js:

var express = require('express'),
    azureMobileApps = require('azure-mobile-apps');

var app = express();

var mobile = azureMobileApps({
    // Explicitly enable the Azure Mobile Apps home page
    homePage: true
});

mobile.tables.import('./tables');

mobile.api.import('./api');

mobile.tables.initialize()
    .then(function () {
        app.use(mobile);    // Register the Azure Mobile Apps middleware
        app.listen(process.env.PORT || 3000);   // Listen for requests
    });

我使用 Postman 发送请求。 邮递员

这是我的控制台日志,如您所见,请求的所有内容都是未定义的。 参数:未定义 查询:未定义 标头:未定义 网址:未定义 状态码:未定义 正文:未定义 ...

【问题讨论】:

  • 删除 'then' 之后的 'function' 并重试。就像这样:.then(() { app.use(mobile); app.listen(process.env.PORT || 3000); });

标签: javascript node.js azure azure-mobile-services


【解决方案1】:

您需要在移动应用服务器中安装body-parser模块,在移动应用入口app.js配置body-parser中间件。然后你可以使用req.body 来获取帖子正文内容。

您可以尝试以下步骤:

  1. 登录 Kudu 控制台站点或移动应用服务器的 Visual Studio Online 编辑器以修改脚本并运行npm 命令。在根目录的package.json 文件中的dependencies 部分下添加像"body-parser": "^1.13.1" 这样的body-parser 模块。运行 npm update 以安装依赖项。
  2. app.js中添加stmt:

    var bodyParser = require('body-parser');
    app.use(bodyParser.json({ limit: '50mb' }));
    app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));`
    
  3. 在您的 Easy API 中尝试代码 sn-p:

    module.exports = {
        "post":function(req,res,next){
            console.log(req.body)
            res.send(req.body)
        }
    };
    
  4. 在 Postman 中,使用 x-www-form-urlencoded 发布您的数据:

【讨论】:

  • 嗨 GaryLiu 感谢您的回答,这确实解决了我的问题。你确实节省了我的时间。
  • 这对我有用。我认为我的错误是我认为仅仅因为我看到 body-parser 位于节点模块中,它是正确的版本并且它可以工作。我认为将它添加到 package.json 并运行 npm install (用于本地安装)就可以了。
【解决方案2】:

改用console.log("%s: %j", k, req[k]);

原因是变量k是一个字符串。因此,要通过其键作为字符串访问成员,您必须使用“数组表示法”

【讨论】:

  • 您好 JasonWihardja,感谢您的回答。在我尝试这个之后,我可以看到一些请求的价值。但是 request["params"], request["body"] 等中仍然没有任何内容。如何获取 Postman 发送的请求内容?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多