无法通过Ionic和Express.js从服务器端的客户端获取数据

时间:2017-08-31 19:32:17

标签: javascript node.js express ionic-framework

此问题之前可能已被回答,但我似乎无法找到正确的答案。我在Ionic项目上工作,我用Node.js和express.js创建了另一个项目来处理我的所有http请求。两者目前都在localhost上运行。当我试图将一些数据从我的客户端发送到服务器端时,我从请求获得的数据在我的console.log(req.body)时看起来像这样:

{ '{"username":"hello@hello.com"}': '' }

我尝试了req.body [用户名]等等来获取数据,但是它只是未定义。

我的处理http请求的控制器如下所示:

$scope.submit = function(){
  var username = $scope.username;
  console.log($scope.data.username);
  $http({
    method: 'POST',
    url: 'http://localhost:8000/api/users',
    data: username,
    headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}
});

Html元素

<input type="text" ng-model="data.username" name="name">

服务器端API如下所示:

router.post('/users', function (req, res) { 
    var username = req.body;

    var newUser = new User({
        username: username
    })

    newUser.save(function (err) {
        if (err) {
            return res.send(500, err);
        }
        return res.json(200, newUser);
    });
});

包含Server.js bodyparser

app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));

1 个答案:

答案 0 :(得分:1)

对象有键和值

{ key: value }

身体上的物体以某种错误的方式发送,因为你发送了一个物品,上面带有键'{“username”:“hello@hello.com”}',其值为''。

我会建议你修改你的nodejs / express服务器的发布方式。但你可以通过一些黑客获得价值。像这样。

 const body = {'{"username":"hello@hello.com"}': '' }

 const keys = Object.keys(body);
 const parsed = JSON.parse(keys[0]);
 console.log(parsed.username);

https://jsfiddle.net/wejh0fsk/2/

编辑:所以我在这里做的是获取对象的所有键。只有一个键'{“用户名”:“hello@hello.com”}'。由于该键是一个字符串,我正在解析它以获取一个对象。现在我有了一个对象

  { username: 'hello@hello.com' }

最后我正在注销用户名。

正确的解决方案是修复您将数据发送到快递服务器的方式。

我不太了解你的控制器。你的ng-model是data.username但是你正在放

var username = $scope.username

哪个应该是

var username = $scope.data.username // (that's at least what you're binding to in your view)

您还希望发送带有帖子的对象,而不仅仅是值

$scope.submit = function(){
  var username = $scope.username;
  console.log($scope.data.username);
  $http({
    method: 'POST',
    url: 'http://localhost:8000/api/users',
    data: { username: username },
    headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}
});

我不确定快速解析器,但我不知道你为什么要两次调用bodyparser。第一个就足够了。