2017-05-15 20 views
-1

'request'ライブラリを使用してserver.jsからauthentication.jsへHTTP POSTリクエストを送信しています。それから、authentication.jsの応答をserver.jsに返信したいのですが、どうすればいいですか?POSTリクエストへの応答を送信するには?

server.js

socket.on('client:authentication', function(authObject){ 
     request.post(
     'http://localhost:8090/authenticate', 
     { json: { username: authObject.username, password: authObject.password } }, 
     function (error, response, body) { 
      if (!error && response.statusCode == 200) { 
       console.log(body) 
      } 
     } 
    ); 
    }); 

authentication.js

app.post('/authenticate', function(req, res){ 
    User.findOne({ 
     username: req.body.username 
    }, function(err, user){ 

     if(!user){ 
     console.log('Authentication failed. User not found'); 
     } 
     else if(user){ 
     if(user.password != req.body.password){ 
      console.log('Authentication failed. Wrong password'); 
     } 
     else{ 

      var token = jwt.sign(user, app.get('secretWord'), { 
      expiresIn : 10800 
      }); 
      //I NEED TO SEND BACK THE TOKEN FROM HERE 
     } 

     } 
    }) 
    }); 

答えて

1

これを試してみてください:

res.send({ 
    token: token 
}); 
+0

あなたが使用することをお勧めします '' 'res.json''を'https://expressjs.com/en/api.html#res.json送信と同じですが、送信しますJSONを送り返したい場合は、自動的に正しいヘッダーが返されます –

関連する問題