2017-12-16 5 views
1

어디에서나 검색했지만 답변을 찾을 수 없습니다. node.js의 동일한 경로에 여러 라우터를 추가 할 수 있습니까? 마찬가지로 : -같은 경로에있는 여러 라우터

는 app.js

var users = require('./routes/users.js'); 
    var users1 = require('./routes/users1.js'); 
    app.use('/' , users); 
    app.use('/' , users1); 

위 수 있습니까?! 아니라면 위의 사항을 어떻게 수정할 수 있습니까? 기본적으로 내가하려는 것은 첫 번째 모듈은 데이터베이스의 정보를 표시하는 것입니다. 사용자가 ADD 버튼을 클릭하면 새로운 정보를 가져 와서 데이터베이스에 저장하는 다른 모듈이 호출됩니다.

전적으로 node.js를 처음 사용했습니다. 어떤 도움이라도 대단히 감사하겠습니다. 감사합니다!

degrees.ejs

<form id = 'degrees' method = POST action = '/main/degrees/add'> 
<table id = "tg" class="tg" align = "center" style="width: 1041px"> 
<colgroup> 
<col style="width: 80px"> 
<col style="width: 80px"> 
<col style="width: 100px"> 
<col style="width: 321px"> 
<col style="width: 425px"> 
<col style="width: 100px"> 
</colgroup> 
    <tr> 
    <th class="tg-yw4l" colspan="2"> Qualification <br/>(fill up like UG | B.TECH)<br><br></th> 
    <th class="tg-yw4l"> Field of Specialisation </th> </label> 
    <th class="tg-yw4l"> Institute </th> </label> 
    <th class="tg-yw4l"> Year of Passing </th> </label> 
    </tr> 

    <tr> 
    <td class="tg-yw4l1" style="width: 200px" contenteditable="true"> <%= Graduation %> </td> 
    <td class="tg-yw4l1" style="width: 200px" contenteditable="true"> <%= Degree %> </td> 
    <td class="tg-yw4l1" style="width: 321px" contenteditable="true"> <%= Specialisation %> </td> 
    <td class="tg-yw4l1" style="width: 525px" contenteditable="true"> <%= Institution %> </td> 
    <td class="tg-yw4l1" style="width: 250px" contenteditable="true"> <%= Year %> </td> 
    </tr> 

    <tr> 
    <td class="tg-yw4l2"><input type="text" name="Graduation" style="width: 90px"></td> 
    <td class="tg-yw4l2"><input type="text" name="Degree" style="width: 90px"></td> 
    <td class="tg-yw4l2"><input type="text" name="Specialisation" style="width: 321px"></td> 
    <td class="tg-yw4l2"><input type="text" name="Institution" style="width: 425px"></td> 
    <td class="tg-yw4l2"><input type="number" name="Years" style="width: 100px"></td> 
    </tr> 

</table> 
</form> 
<button onclick = "add()"> + ADD </button> 

</body> 

<script type="text/javascript"> 

    function add() 
    { 
     var tables = document.getElementById("tg"); 
     var rows = tables.insertRow(-1); 
     var cell1 = rows.insertCell(0); 
     var cell2 = rows.insertCell(1); 
     var cell3 = rows.insertCell(2); 
     var cell4 = rows.insertCell(3); 
     var cell5 = rows.insertCell(4); 

     cell1.innerHTML = "<div contenteditable> </div>"; 
     cell2.innerHTML = "<div contenteditable> </div>"; 
     cell3.innerHTML = "<div contenteditable> </div>"; 
     cell4.innerHTML = "<div contenteditable> </div>"; 
     cell5.innerHTML = "<div contenteditable> </div>"; 
    } 
</script> 

노선/

var express = require('express'); 
    var router = express.Router(); 
    var MongoClient = require('mongodb').MongoClient; 
    var url = 'mongodb://<username>:<password>@ds141434.mlab.com:41434/teacherspro'; 
    var _db; 

    MongoClient.connect(url , function(err,db){ 
     if (err) return; 
     _db = db; 
    }); 

    router.post('/' , function (req,res){ 
     _db.collection('project1').find({"UserName" : "karan"} , {Graduation : 1 , Degree : 1 , Specialisation : 1 , Institution : 1 , Year : 1 }).forEach(function(fifa){ 
      console.log('loaded 2 time!'); 
      res.render('degrees' , {Graduation : fifa.Graduation , Degree : fifa.Degree , Specialisation : fifa.Specialisation , Institution : fifa.Institution , Year : fifa.Year});  
     }); 
    }); 
module.exports = router; 

노선/user1.js

var express = require('express'); 
var router = express.Router(); 
var MongoClient = require('mongodb').MongoClient; 
var url = 'mongodb://<username>:<password>@ds141434.mlab.com:41434/teacherspro'; 
var _db; 

MongoClient.connect(url , function(err,db){ 
    if (err) return; 
    _db = db; 
}); 

router.post('/' , function (req,res) { 
    res.render('degrees'); 
     var users = { 
      Graduation : req.body.Graduation.Graduation, 
      Degree : req.body.Degree, 
      Specialisation : req.body.Specialisation, 
      Institution : req.body.Institution, 
      Year : parseInt(req.body.Year) 
     }; 
     _db.collection('project1').insertOne({users : users} , function(err){ 
      if(err) {console.log('no insert!');} 
      console.log('Data inserted!'); 
     }); 
}); 

module.exports = router; 
+0

시도해 보셨습니까? 오류가 있습니까? –

+0

예, 다음 경로가 호출되지 않습니다 –

+0

쓰기는 가능하지만 작동하지 않을 수 있습니다. 경로 지정 계층이 있습니다. 두 번째는 절대로 실행되지 않습니다. –

답변

1

users.js이 허용 , 경로를 일치시키고 next()을 호출하지 않고 응답을 보내는 첫 번째 처리기는 우선권을 가지며 다른 경로 처리기는 호출되지 않습니다. Express는 경로가 선언 된 순서대로 일치합니다. 일치하는 첫 번째 것은 경로에서 첫 번째 균열을 얻습니다. next()을 호출하여 의도적으로 다른 처리기로 라우팅하도록 Express에 지시하지 않으면 다른 라우트 핸들러가 호출되지 않습니다.

라우트 핸들러가 호출 된 후에도 라우팅을 계속하려면, next()을 호출하여 Express가 라우트와 일치하는 다른 라우트 핸들러를 계속 찾도록 지시 할 수 있습니다.

app.use('/' , users); 

// then users could be this: 
function users(req, res, next) { 
    if (want to handle route here) { 
     res.send(someResponse); 
    } else { 
     // tell Express to continue routing to other handlers 
     next(); 
    } 
} 

그래서 내가 ADD 버튼을 클릭 ..if 데이터베이스에서 내 정보를 렌더링 한 경로가 있다고 가정 할 수 있습니다, 새 열은 새로운 정보, 코드 및 세부있는 다른 모듈에 들어가는 나타납니다 .. 리디렉션하고 싶지 않지만 새로운 정보를 얻기 위해 동일한 렌더링 된 페이지를 다시 사용하려면 어떻게해야합니까?

동일한 버튼을 사용하여 다시 프로세스를 반복하려면 문제가 없습니다. 동일한 경로가 실행되고 작업이 반복됩니다.

다른 경로를 사용하여 다른 작업을 구현하려는 경우 적절한 디자인이 아닙니다. 주어진 경로는 주어진 기능을 가져야합니다. 사이트의 다른 기능에 대한 기능을 변경하려면 다른 경로를 사용하십시오. 양식 게시는 다음 작업을 위해 다른 양식을 제공하는 새 콘텐츠를 반환 할 수 있습니다. 페이지에서 Javascript를 사용하여 다시로드되지 않는 페이지 내의 로직을 변경할 수 있습니다. 이 질문에 대해 좀더 구체적으로 설명하기 위해, 우리는 실제 코드/html을보고 무슨 일이 일어나고 있는지, 정확히 무엇을 추천하는지 알아야합니다. 그러나 주어진 경로는 서로 다른 시간에 두 가지 일을해서는 안됩니다. 그것은 잘못된 디자인입니다.

쿼리 매개 변수를 경로와 함께 사용하여 추가 정보를 경로 처리기에 전달할 수도 있지만 쿼리 매개 변수를 사용하여 경로 기능을 완전히 변경하는 것은 바람직하지 않습니다.경로는 인수가있는 함수 호출처럼 작동해야하며 일반적으로 호출 할 때마다 동일한 작업을 수행해야합니다 (전달하는 인수의 의미에 따라 다름).