Node.js 如何发送对POST请求的响应?
我正在使用“请求”库将HTTP POST请求从server.js发送到authentication.js。然后我想从authentication.js向server.js发回一个响应,我该怎么做 server.jsNode.js 如何发送对POST请求的响应?,node.js,express,request,Node.js,Express,Request,我正在使用“请求”库将HTTP POST请求从server.js发送到authentication.js。然后我想从authentication.js向server.js发回一个响应,我该怎么做 server.js socket.on('client:authentication', function(authObject){ request.post( 'http://localhost:8090/authenticate', { json: { usern
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)
}
}
);
});
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
}
}
})
});
authentication.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)
}
}
);
});
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
}
}
})
});
试试这个:
res.send({
token: token
});
您可能希望使用
res.json
它与send相同,但是如果您想发送回json,它会自动发送正确的头