我正在使用请求库对本地托管的API(MailDev客户端)进行休息调用
分别运行各个组件时,我可以删除,发送和阅读电子邮件。但是,当我一起运行时,我只能删除并发送。 Get请求始终返回空响应。
var http = require('http');
var request = require('request');
var nodemailer = require('nodemailer');
var urlStr = 'http://localhost:1080/email/all'
var options = {
url: urlStr,
method: 'DELETE'
};
request.del('http://localhost:1080/email/all')
var transporter = nodemailer.createTransport({
port: 1025,
ignoreTLS: true,
});
const mailOptions = {
from: 'email1@googlemail.com', // sender address
to: 'email2@yahoo.com', // list of receivers
subject: 'Hello world', // Subject line
html: '<p>Hello world, stay happy :)</p>'// plain text body
};
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else
console.log();
});
console.log("getting emails");
request('http://localhost:1080/email/',function(err,res,body){
if(err){console.log(err);}
console.log(body);
});
为什么获取请求只能孤立地工作?
由于
答案 0 :(得分:1)
你正在做的是同时解雇所有请求。不能保证哪个请求首先完成,因此您调用它们的顺序并不能保证它们将以相同的顺序执行。试试这个:
var http = require('http');
var request = require('request');
var nodemailer = require('nodemailer');
var urlStr = 'http://localhost:1080/email/all'
var options = {
url: urlStr,
method: 'DELETE'
};
var transporter = nodemailer.createTransport({
port: 1025,
ignoreTLS: true,
});
const mailOptions = {
from: 'email1@googlemail.com', // sender address
to: 'email2@yahoo.com', // list of receivers
subject: 'Hello world', // Subject line
html: '<p>Hello world, stay happy :)</p>'// plain text body
};
deleteEmails(function(){
sendMail(mailOptions, function(){
getEmails(function(res, body){
console.log(body);
})
})
})
function deleteEmails(successCallback){
request.del('http://localhost:1080/email/all', function (err){
if(err)
console.log(err)
else if(successCallback) {
successCallback()
}
})
}
function sendMail(mailOptions, successCallback){
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else if(successCallback) {
successCallback()
}
});
}
function getEmails(successCallback){
console.log("getting emails");
request('http://localhost:1080/email/',function(err,res,body){
if(err){
console.log(err);
} else {
successCallback(res, body)
}
});
}