【问题标题】:Asynchronous communication with Android(client) and Node.js(server)与 Android(客户端)和 Node.js(服务器)的异步通信
【发布时间】:2018-05-19 17:17:04
【问题描述】:

我想与 Android 和 Node.js 进行通信。

我实现了程序,当它们在同一个网络上时运行良好(我的意思是同一个 WIFI)。但是当我将我的安卓手机与wifi断开连接并连接到移动数据时,就无法通信了。经过一番搜索,发现存在跨域问题。 但我找不到适合我情况的解决方案。 请问你能帮我解决这个问题吗?

这是我的服务器端代码(server.js)。

var https = require('https');
var express = require('express');
var fs = require('fs');
var app = express();
var port = 9000;
var cors = require('cors');

var welcome = "new msg from server!";

app.get('/get', function(req, res) {
    console.log('>> send new msg to client...');
    res.json(welcome);
})
app.post('/post', function(req, res) {
    console.log('<< receive new msg from client...');
    var info_from_client;
    req.on('data', function(data) {
        info_from_client = JSON.parse(data);
    })
    req.on('end', function(data) {
        var log_temp = "contents : \nname = " + info_from_client.user_name +          "\nfinger_print = " + info_from_client.finger_print;
    console.log(log_temp);
    res.write(log_temp);
    res.end();
    })
})

app.listen(port, function() {
    console.log('now server is starting...');
})

这是我的客户端代码。

public class SendToServer extends AsyncTask<String, String, String> {

private TextView tv;
private int action;
private int get = 1;
private int post = 2;


public SendToServer (TextView tv, int action) {
    this.tv = tv;
    this.action = action;
}

public String get_action(HttpURLConnection connection) {

    InputStream stream;
    BufferedReader reader = null;
    StringBuffer buffer;

    try {
        connection.connect();

        stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        buffer = new StringBuffer();
        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        return buffer.toString();
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {

            if (reader != null) {
                reader.close();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }//end of finally

    return null;

}
public String post_action(HttpURLConnection connection) {

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.accumulate("user_name", "Na Jun Yeop");
        jsonObject.accumulate("finger_print", "12388452218");
    } catch (JSONException e) {
        e.printStackTrace();
    }


    OutputStream outputStream;
    InputStream inputStream;
    BufferedWriter writer = null;
    BufferedReader reader = null;
    StringBuffer buffer;

    try {
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "text/html");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        outputStream = connection.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(outputStream));

        writer.write(jsonObject.toString());
        writer.flush();
        writer.close();

        inputStream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        buffer = new StringBuffer();
        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        return buffer.toString();
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {

            if (reader != null) {
                reader.close();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }//end of finally

    return null;
}

@Override
protected String doInBackground(String... strings) {

    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {
        URL url = new URL(strings[0]);
        connection = (HttpURLConnection)url.openConnection();

        if (action == get) {
            return get_action(connection);
        }
        else if (action == post) {
            return post_action(connection);
        }

        connection.connect();

        InputStream stream = connection.getInputStream();

        reader = new BufferedReader(new InputStreamReader(stream));

        StringBuffer buffer = new StringBuffer();

        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        return buffer.toString();


    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {

            if (reader != null) {
                reader.close();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }//end of finally


    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    tv.setText(result);
}

【问题讨论】:

    标签: android node.js cross-domain


    【解决方案1】:

    为了解决这个问题,您需要让您的 Node.js 服务器使用 SSL 证书或安全 https。对于本地测试,您应该只尝试使用相同的本地网络。 尝试在您的请求中更新以下参数,看看它是否有效

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS
    Access-Control-Allow-Headers: Content-Type
    

    【讨论】:

    • 感谢您的回复,请问有什么办法可以通过jsonp或者proxy来解决??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多