简体   繁体   English

客户端与服务器端数据操作

[英]Client-side vs server-side data manipulation

I just learned how to access express local variables in client-side JS: 我刚刚学习了如何在客户端JS中访问表达局部变量:

https://stackoverflow.com/questions/34618426/express-handlebars-local-variables-in-client-side-js https://stackoverflow.com/questions/34618426/express-handlebars-local-variables-in-client-side-js

But this opened a whole new can of worms... Now I don't know what data manipulation to do server side (within the route) and which to do client-side. 但是,这打开了一个全新的蠕虫罐……现在,我不知道要在服务器端(在路由内)进行哪些数据操作,而要在客户端进行哪些数据操作。

For example: Here I am cutting the description property of each database item, so that the first 100 characters can be used as a preview in a featured listing collage. 例如:在这里,我剪切每个数据库项目的description属性,以便可以将前100个字符用作功能列表拼贴中的预览。

//routes/index.js
router.get('/', isAuthenticated, function (req, res, next) {
  //Fetching data to populate newest listings collage
  User.find({role: 'organization'}).sort({datecreated: -1}).limit(6).exec(function (err, docs) {
    docs.forEach(function(item){
      item.description = item.description.slice(0,100);
    });
    console.log(docs[0].description);
    res.render('index.hbs', {
      user: req.user, 
      orgsfeatured: docs, 
      message: req.flash('message')
    })
  });
});

Is it more typical/ performant/ maintainable to just send the entire array of objects to the client-side javascript to be sliced? 将整个对象数组发送到客户端javascript进行切片是否更典型/更高效/更可维护?

I know it's a balance between running up the client cpu load vs the server load, but there must be some best practices . 我知道在运行客户端cpu负载和服务器负载之间是一种平衡,但是必须有一些最佳实践 Let me know if I am not being clear. 如果我不清楚,请告诉我。 Thanks!! 谢谢!!

In my experience you can't take a "one-size fits all" approach. 以我的经验,您不能采取“一刀切”的方法。

In your posted example, you are limiting your results to 6, and truncating to 100 chars. 在您发布的示例中,您将结果限制为6,并截断为100个字符。 Doing 6 slices, wouldn't be a huge hit CPU-wise for either side. 做6片,对于任何一方在CPU方面都不是一个大打击。 If the item.description could potentially be thousands of chars each, then do the slice server side, to prevent unneeded data flow. 如果item.description可能每个都有数千个字符,则请在分片服务器端进行操作,以防止不必要的数据流。 Or, if thousands of users could potentially be calling this code at the same time, and the item.descriptions are close to 100 chars, let the thousands of web browsers do the work. 或者,如果成千上万的用户可能同时调用此代码,并且item.descriptions接近100个字符,则让成千上万的Web浏览器完成工作。

Not knowing anything about your project, would it be possible to not slice the descriptions at all? 对您的项目一无所知,是否有可能根本不分割描述? You may need the entire description in a popover, or use may use it in some search/filter mechanism. 您可能需要在弹出窗口中使用整个描述,或者可以在某些搜索/过滤器机制中使用它。 If your design dictates that the strings need truncating, then let CSS do that task. 如果您的设计指示字符串需要截断,那么让CSS来完成该任务。

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

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