Node.js-处理对服务器的Ajax请求的更好方法 [英] Nodejs - A better way to handle ajax request to the server
问题描述
现在我遇到了在nodeJS服务器上管理ajax请求的问题.目前,我有这个系统,但是它很丑,效率不高.
Now I ran into a problem with managing ajax requests on nodeJS server. Currently I have this system it works, but it's ugly and not that efficient.
router.post('/get', function(req, res) {
var request = req.body.request;
if (request == null) {
res.json({success: 'false', error: 'Response returned null'});
return;
}
if (request == "render_page") {
var page = req.body.page;
if (page == null) {
res.json({success: 'false', error: 'Page returned null'});
return;
}
res.render(page);
} else if (request == "render_article") {
var temp = {
articles: [
{title: 'ABC', text: 'This is a test article'},
{title: 'XYZ', text: 'Just another random article'}
]
};
res.render('template/article-format', temp);
} else {
res.json({success: 'false', error: "Unknown request " + request});
}
有没有更好的方法可以做到这一点,甚至可以使其变得动态起来?另外,如果发生问题,服务器也喜欢崩溃,那么就是这样.
Is there a better way to do this and even maybe make it dynamic? Also the server likes to crash if something goes wrong so there's that.
推荐答案
您似乎正在与GET和POST的概念作斗争.GET请求应该用于获取内容(例如页面).但是,您已经指定了POST请求,然后将其命名为/get,然后将上下文放入请求正文中.
You seem to be fighting with the concepts of GET and POST. GET requests are supposed to be used for fetching things (like pages). Yet, you have specified a POST request, then named it /get, and then put the context in the request body.
如果仅在GET请求中利用某些参数,则无需发送带有正文的帖子(我假设您正在使用POST请求,因为您认为自己需要能够发送请求上下文数据(在这种情况下为页面名称).
If you simply leveraged some parameters in your GET requests, then you don't need to send a post with body (which I'm assuming you are using a POST request because you thought you needed to be able to send the request context data, in this case the page name).
因此,您有一堆被称为发布请求的get请求.真的,您想要的是这样的东西:
So, you have a bunch of get requests that are being called as post requests. Really what you want is something like this:
router.get('/page/:page', function(req, res) {
var page = req.params.page;
// Logic here
});
对于处理空"页面,您只需将它们自动路由到/page网址(因为如果没有参数,则只是/page网址).
And for handling the "null" page, you just route them to the /page url automatically (since if there is no parameter, it is just the /page url).
为进一步阅读,我将查看:
For further reading, I'd look over:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
http://expressjs.com/4x/api.html#req
这篇关于Node.js-处理对服务器的Ajax请求的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!