2015-09-08 19 views
1

例如,當路徑是製作REST API +反應,而不必其他包

/json/users/4 

流星應用程序必須返回JSON像

{ 
    id: 4, 
    name: 'Alex' 
} 

我使用reactrouter:react-路由器用於客戶端路由。我知道reactrouter:react-router-ssr,但如何使用它來響應原始json?並使其與現有客戶端路由不衝突?

回答

2

我找到了答案。流星的默認的webapp包將幫助(doc):

WebApp.connectHandlers.use("/hello", function(req, res, next) { 
    res.writeHead(200); 
    res.end("Hello world from: " + Meteor.release); 
}); 

我把這個服務器文件夾。其他路線將照原樣呈現。
因此,有更多的有用的例子(ES6):

WebApp.connectHandlers.use("/payme", function(req, res, next) { 
    res.writeHead(200, {'Content-Type': 'application/json'}); 
    if (req.method === 'POST') { 
     req.on('data', (chunk) => { 
      const body = chunk.toString(); 
      if (body.length < 1e6) { 
       const params = body.split('&').reduce((result, item) => { 
        const [key, val] = item.split('='); 
        //do it for utf-8 values (I use it for cyrillic strings) 
        result[key] = unescape(decodeURI(val)).replace(/\+/g, ' '); 
        return result; 
       }, {});      //post method params 

       //do something and get resulting json 

       res.end(JSON.stringify(result)); 
      } else 
       res.end(JSON.stringify({error: 'too big query'})); 
     }); 
    } else 
     res.end(JSON.stringify({error: 'isnt post req'})); 
}); 

req.query可以用來獲得GET PARAMS。