简体   繁体   English

节点JS返回未定义?

[英]Node JS return undefined?

I am using a basic node.js introduction script, and i am passing in a argument in the command line. 我正在使用基本的node.js简介脚本,并且正在命令行中传递参数。 i want this argument to be passed back to the client after it has run. 我希望此参数在运行后传递回客户端。 I can pass back anything that is pure text or values, but i can't pass back a variable containing the same information. 我可以传回纯文本或值的任何内容,但不能传回包含相同信息的变量。

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8"/>
  <title>get test</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">
  </script>
</head>
<body>
  <h1>Get Test</h1>
  <div id="test"></div>
  <script>
    $(document).ready(function() {
      $.ajax({url: 'http://localhost',dataType: "jsonp",jsonpCallback: "_testcb",cache: false,timeout: 5000,success: function(data) {
          $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          alert('error ' + textStatus + " " + errorThrown);
        }
      });
    });
</script>
</body>
</html>

And this is my server code: 这是我的服务器代码:

var http = require('http');
var arr = new Array();
http.createServer(function (req, res) {
  res.writeHead(200);

  // print process.argv
  process.argv.forEach(function(val, index, array) {
    console.log(index + ': ' + val);
    arr[index] = val;
    res.write("Size" + val);
    res.end('_testcb(\'{"Size: \' + val + \'"}\')');
  });


  console.log(arr[2]);
}).listen(80);

So my question is, how do i pass back objects/ variables/ arrays rather than static text? 所以我的问题是,如何传递对象/变量/数组而不是静态文本?

If you're trying to send data to the client, you need to serialize the data into JSON in order send the values to the client. 如果您尝试将数据发送到客户端,则需要将数据序列化为JSON,以便将值发送到客户端。

For example, to send all of the arguments to the client, you can simply change the method to: 例如,要将所有参数发送给客户端,您只需将方法更改为:

http.createServer(function (req, res) {
  res.writeHead(200);

  res.write("_testcb(" + JSON.stringify(process.argv) + ")");
}).listen(80);

Which will make data (on the client) an array of all the arguments to the process. 这将使data (在客户端上)成为流程所有参数的数组。

If you want to pass a different type of object, create the variable the way that you want it, and again, use JSON.stringify to convert the data to text which can then be sent. 如果要传递其他类型的对象,请按所需的方式创建变量,然后再次使用JSON.stringify将数据转换为可以发送的文本。 For example: 例如:

http.createServer(function (req, res) {
  res.writeHead(200);

  // create an empty object
  var data = {};

  // add a size attribute
  data["Size"] = process.argv[1];

  res.write("_testcb(" + JSON.stringify(data) + ")");
}).listen(80);

The key to all of this, is the JSON.stringify method - it allows you to convert your variables into JSON which the client then parses to be data. 所有这些的关键是JSON.stringify方法-它允许您将变量转换为JSON,然后客户端将其解析为数据。

You can only pass text back and forth, but you can pass text in JSON format and parse it on the client/server. 您只能来回传递文本,但是可以以JSON格式传递文本并将其解析在客户端/服务器上。

EDIT 编辑

Just in case I misinterpreted this question and you are looking to get the command line arguments that your nodejs process was started with, take a look at this thread: 以防万一我误解了这个问题,而您正在寻找开始使用nodejs进程的命令行参数,请看以下线程:

How do I pass command line arguments? 如何传递命令行参数?

The arguments are stored in process.argv 参数存储在process.argv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM