简体   繁体   English

如何支持与node.js的api和web界面数据交互?

[英]How to support both api and web interface data interaction with node.js?

Im having major trouble separating api calls for our mobile app and for web interface, basically code is the same but the responses should be different (html as for web and json for api calls from app) 我在为我们的移动应用程序和网络界面分离api调用时遇到了很大的麻烦,基本上代码是相同的但响应应该是不同的(对于web和json,来自应用程序的api调用的html)

So right now I have routing like this: 所以现在我有这样的路由:

  app.post('/post', auth.needed, posts.create)
  app.post('/addPost', posts.createJson)

first is used for web app and second one for 第一个用于Web应用程序,第二个用于

BUT the logic inside "posts.create" is the same, its basically uploading image and saves post to db, right now I have duplicated code and seeking for structuring advice how to do this properly and what is the best practice for similar situations Thanks! 但是“posts.create”里面的逻辑是一样的,它基本上传图像并将帖子保存到db,现在我有重复的代码并寻求结构建议如何正确地做到这一点以及类似情况的最佳实践谢谢!

exports.create = function (req, res) {
  var post= new Post(req.body)
  post.user = req.user
  //custom logic 
  post.uplSave(req.files.image, function (err) {
    if (!err) {
      return res.redirect('/posts/'+post._id)
    }
  }
}

exports.createJson = function (req, res) {
  var post = new Post(req.body)
  post.user = req.user
  //custom logic 
  post.uplSave(req.files.image, function (err) {
    if (!err) {
      res.json({
        data: post,
      })
    }
  }
}

Sounds like you can benefit from using res.format , so you can re-use your handler: 听起来你可以从res.format受益,所以你可以重用你的处理程序:

exports.create = function (req, res) {
  var post  = new Post(req.body);
  post.user = req.user;
  post.uplSave(req.files.image, function (err) {
    if (err)
      return res.send(500); 
    res.format({
      default : function() {
        res.redirect('/posts/' + post._id);
      },
      json    : function() {
        res.json({ data : post });
      }
    });
  });
}

If a client explicitly tells the server that it wants a JSON response (using an Accept: application/json header), the server will return JSON. 如果客户端显式告诉服务器它想要JSON响应(使用Accept: application/json标头),则服务器将返回JSON。 Otherwise (the default case) it will generate a redirect. 否则( default情况下)它将生成重定向。

Since this depends on a client doing The Right Thing™, which might not be the case in your situation, another solution would be to create a partial function for your handler, passing the return type as a fixed argument: 由于这取决于客户端正在使用The Right Thing™(在您的情况下可能不是这种情况),另一种解决方案是为您的处理程序创建一个部分函数 ,将返回类型作为固定参数传递:

app.post('/post', auth.needed, posts.create.bind(posts, 'default'));
app.post('/addPost', posts.create.bind(posts, 'json'));

// your handler would look like this:
exports.create = function(type, req, res) {
  ...
  if (type === 'json')
    return res.json(...);
  return res.redirect(...);
};

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

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