从node js服务器响应发送整数值

问题描述 投票:0回答:1

我有一个node js服务器的实现,我想发送一些值到一个Android(Java)客户端。node js服务器的方法如下。

app.get('/GetValues*', function (request, response) {
    // Request needs to be a GET
    if (request.method == 'GET') {

        var username = request.query.account;
        var time_now = Date.now();

        var db = database('./database.db'); 
        var row_account = db.prepare('SELECT SCORE score, STARTED_STUDY_SERVER_MILLIS timestamp, DAYS_TOTAL days_total FROM ACCOUNTS WHERE NAME = ?').get(username);

        var score = row_account.score;
        var days_total = row_account.days_total;
        var days_count = time_now - row_account.timestamp;
        var minutes_count = time_now - row_account.timestamp;

        var statement = db.prepare("UPDATE ACCOUNTS SET DAYS_COUNT = ?, MINUTES_COUNT = ? WHERE ID = ?");
        statement.run(days_count,minutes_count,getAccountID(db, request.query.account));

        var row_usage = db.prepare('SELECT DURATION_ENABLED duration_enabled, DURATION_DISABLED duration_disabled FROM USAGE WHERE NAME = ?').get(username);
        var duration_enabled = row_usage.duration_enabled;
        var duration_disabled = row_usage.duration_disabled;
    }
});

我想发送的值 score (整数)。days_total (整数)。days_count (整数)。minutes_count (长)。duration_enabled (长)。duration_disabled 长)给客户。

我怎么能把它发送给客户端呢?我认为response.send()只接受字符串。当收到这些值时,我如何在Java中进行解析?

java android node.js
1个回答
2
投票

由于你需要一次性发送所有这些值,所以在这种情况下,通常用JSON来响应。在express中,你可以使用以下方法发送JSON响应 response.send()response.json() 像这样。

app.get('/GetValues*', function (request, response) {
  // ... your db operations here, then
  response.json({
    score: score,
    days_total: days_total,
    days_count: days_count,
    minutes_count: minutes_count,
    duration_enabled: duration_enabled,
    duration_disabled: duration_disabled
  });
});

这将发送一个响应 Content-Type: application/json 和一个JSON字符串在主体中,看起来像这样。

{"score":12,"days_total":12,"days_count":12,"minutes_count":12,"duration_enabled":12,"duration_disabled":12}

然后你只要 解析 在你的Java代码中。


顺便说一下,这一行

if (request.method == 'GET') {

是不必要的。通过 app.get(),快递只处理 GET 反正请求。

© www.soinside.com 2019 - 2024. All rights reserved.