【问题标题】:How do I receive and use a JSON object on the client-side from the server (Node JS and Express)?如何在客户端从服务器(Node JS 和 Express)接收和使用 JSON 对象?
【发布时间】:2015-03-02 22:34:12
【问题描述】:

我正在尝试做一些看似非常简单的事情,但我无法解决。用户可以使用带有POST 方法的HTML 表单提交一些文本。然后将其发送到 API 进行处理,并返回一个 JSON 对象。然后我只希望app.js 文件将这个 JSON 对象发回,这样我就可以使用 JQuery 来处理它。 这是我的app.js 中的.post 方法

app.post('/', function(req, res){
 console.log("starting app.post");

  // See User Modeling API docs. Path to profile analysis is /api/v2/profile
  // remove the last / from service_url if exist
  var parts = url.parse(service_url.replace(/\/$/,''));

  var profile_options = { host: parts.hostname,
    port: parts.port,
    path: parts.pathname + "/api/v2/profile",
    method: 'POST',
    headers: {
      'Content-Type'  :'application/json',
      'Authorization' :  auth }
    };

  // create a profile request with the text and the https options and call it
      create_profile_request(profile_options,req.body.content)(function(error,profile_string) {
        if (error) {res.render('home.html',{'error': error.message});
                        console.log("errormessage: "+error.message);
      }
    else {
      // parse the profile and format it
      var profile_json = JSON.parse(profile_string);
      var flat_traits = flatten.flat(profile_json.tree);      
      // Extend the profile options and change the request path to get the visualization
      var fileName="file 1"; //this will eventually be imported automatically
      //console.log(flat_traits);     
      var scoreObject={"title":fileName, "percentage":functions.matchPercentage(flat_traits)}
  res.send(scoreObject); //this is what I assume should send this back client-side      
          });
    }
  });
    });

// creates a request function using the https options and the text in content
// the function that return receives a callback
var create_profile_request = function(options,content) {
  return function (/*function*/ callback) {
    // create the post data to send to the User Modeling service
    var post_data = {
  'contentItems' : [{ 
    'userid' : 'dummy',
    'id' : 'dummyUuid',
    'sourceid' : 'freetext',
    'contenttype' : 'text/plain',
    'language' : 'en',
    'content': content
  }]
    };
// Create a request to POST to the User Modeling service
var profile_req = https.request(options, function(result) {
  result.setEncoding('utf-8');
  var response_string = '';

  result.on('data', function(chunk) {
    response_string += chunk;
  });

  result.on('end', function() {

    if (result.statusCode != 200) {
      var error = JSON.parse(response_string);
      console.log("status: "+result.statusCode);
      callback({'message': error.user_message}, null);
      console.log(error.user_message);
    } else
      callback(null,response_string);
  });
});

profile_req.on('error', function(e) {
  callback(e,null);
});

profile_req.write(JSON.stringify(post_data));
profile_req.end();
  }
 };

所以我认为res.send 是将数据传递到客户端的原因,但是我如何在客户端接收数据?这是我对 JScript 的尝试:

$.getJSON('/').done(function(data){
$('#resultsList').append('<li data-icon="arrow-r" data-iconpos="right" id="'+
        data.title+'">  <a href="#breakdownDialog"> <div id="cvResults"><h3>'+
        data.title+'</h3>   <span>'+data.percentage+
        '%</span></div></a><div id="output"></div></li>');
console.log(data.title+data.percentage);
}
});

我想从 JSON 对象中获取一些值并将它们放在现有 HTML 页面上的列表中。目前,这只是将我带到另一个空白页,上面写着Undefined。 我应该如何从服务器获取 JSON 数据?

编辑:这是我用来提交数据的 HTML 表单:

<form method="POST" id="submitForm">
                <fieldset>
                    <textarea id="textArea" required="true" rows="5" name="content"></textarea>
                    <button class="btn btn-block" type="submit">
                            Analyse         
                    </button>
                </fieldset>
                </form>

【问题讨论】:

  • 如果返回json,为什么不使用res.json
  • 您是否在表单元素上设置了 target="_blank" 属性?将问题中的 html 作为 weel 会很有用
  • 我现在添加了 HTML

标签: javascript json node.js express client-side


【解决方案1】:

您确定要发送带有res.send() 的json 吗?尝试设置标题 res.set('Content-Type', 'application/json') 或使用此 res.json() 而不是 res.send()

【讨论】:

  • 这很好。虽然我尝试了这个,但我在客户端仍然遇到同样的问题,似乎无法让它按预期工作。我的 JQuery 代码有问题吗?
  • 我猜问题在于使用纯 HTML 提交表单。在我看来,使用 AJAX 会更好。使用此代码 - jsfiddle.net/1bvxr56v 您将在不重新加载页面的情况下收到您的数据,因此可能需要更改成功方法。
  • 对我来说,你会设置在那里发布的方法是有道理的……纯粹通过 HTML 提交它对我来说没有多大意义。现在我不明白服务器端代码是如何变化的。有大量帐户信息(如 URL、用户名等)应该是客户端的。我可以以某种方式将客户端数据传递到服务器端吗?
  • 您使用 AJAX 传递客户端数据。您可以使用 val() 等 jQuery 方法从输入等中获取这些数据。在服务器上,它可以在 req.body 对象中访问。
猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
相关资源
最近更新 更多